<Window x:Class="WPF5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Name="MyWindow" Height="350" Width="525"> <Grid Margin="0,0,276,122"> <DataGrid> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Visibility="{Binding ElementName=MyWindow, Path=WylzColumn}"/> <DataGridTextColumn Header="年龄"/> </DataGrid.Columns> </DataGrid> <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="319,155,-153,0" Visibility="{Binding ElementName=MyWindow, Path=WylzColumn}"/> </Grid> </Window>
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public static readonly DependencyProperty WylzColumnProperty = DependencyProperty.Register("WylzColumn", typeof(Visibility), typeof(MainWindow), new FrameworkPropertyMetadata(Visibility.Collapsed)); //注册依赖项属性 public Visibility WylzColumn { get { return (Visibility)GetValue(WylzColumnProperty); } set { SetValue(WylzColumnProperty, value); } } }
窗口有一个Visibility 类型的依赖性属性WylzColumn。窗体中有一个DataGrid,”姓名”列的Visibility属性值绑定到窗体的WylzColumn值上,同时,有一个Button的Visibility属性值也是绑定到窗体的WylzColumn值上。
可结果是,Button的绑定有效果,Button也没有显示,但是”姓名”列的绑定却没有效果,仍然显示。
这是什么原因呢?