我对XAML还比较陌生,但很喜欢学习它。我真正遇到困难的是将属性绑定到DataTemplate
中的元素。
我创建了一个简单的WPF示例来(希望)解释我的问题。
在这个示例中,我试图将DataTemplate
中的CheckBox
的Visibility
属性绑定到我的视图模型中的属性。(仅用于学习/演示场景)
我有一个名为Item
的简单数据模型,但在本示例中并不太相关。
class Item : INotifyPropertyChanged
{
// Fields...
private bool _IsRequired;
private string _ItemName;
还有一个名为ItemViewModel的相对简单的视图模型。
class ItemViewModel : INotifyPropertyChanged
{
private ObservableCollection<Item> _Items;
private bool _IsCheckBoxChecked;
private bool _IsCheckBoxVisible;
public ObservableCollection<Item> Items
{
get { return _Items; }
set { _Items = value; }
}
public bool IsCheckBoxChecked
{
get { return _IsCheckBoxChecked; }
set
{
if (_IsCheckBoxChecked == value)
return;
_IsCheckBoxChecked = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("IsCheckBoxChecked"));
PropertyChanged(this, new PropertyChangedEventArgs("IsCheckBoxVisible"));
}
}
}
public bool IsCheckBoxVisible
{
get { return !_IsCheckBoxChecked; }
set
{
if (_IsCheckBoxVisible == value)
return;
_IsCheckBoxVisible = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("IsCheckBoxVisible"));
}
< p >(出于简洁起见,构造函数和INotifyPropertyChanged
实现已省略。)
在MainPage.xaml中布置的控件如下。
<Window.Resources>
<local:VisibilityConverter x:Key="VisibilityConverter"/>
</Window.Resources>
<Window.DataContext>
<local:ItemViewModel/>
</Window.DataContext>
<Grid>
<StackPanel>
<CheckBox x:Name="checkBox" Content="Hide CheckBoxes" FontSize="14" IsChecked="{Binding IsCheckBoxChecked, Mode=TwoWay}" />
<ListView ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch" >
<ListView.ItemTemplate >
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ItemName}"/>
<CheckBox Grid.Column="1" Visibility="{Binding IsCheckBoxVisible, Converter={StaticResource VisibilityConverter}}" >
<CheckBox.DataContext>
<local:ItemViewModel/>
</CheckBox.DataContext>
</CheckBox>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Orientation="Horizontal" Margin="4,4,0,0">
<TextBlock Text="IsCheckBoxVisible:"/>
<TextBlock Text="{Binding IsCheckBoxVisible}" Margin="4,0,0,0" FontWeight="Bold" />
</StackPanel >
<Button Content="Button" Visibility="{Binding IsCheckBoxVisible, Converter={StaticResource VisibilityConverter}}" Margin="4,4,4,4"/>
</StackPanel>
</Grid>
'隐藏复选框' 复选框绑定了 'IsCheckBoxChecked' 属性,用于更新 'IsCheckBoxVisible' 属性。我还在 DataTemplate
下面添加了一些额外的控件来证明(对我自己来说)一切正常工作。
我也实现了 Jeff Wilcox 的值转换器。(感谢他。)http://www.jeff.wilcox.name/2008/07/visibility-type-converter/
当我运行应用程序时,勾选和取消 '隐藏复选框',DataTemplate
之外的控件如预期工作,但遗憾的是,数据模板内的 Checkbox
保持不变。
我已经成功地使用:IsVisible="{Binding IsChecked, Converter={StaticResource VisibilityConverter}, ElementName=checkBox}"
但我不仅仅是试图模仿另一个控件,而是基于一个值做出决策。
我真的非常感谢您能提供的任何帮助或建议。
谢谢。