我觉得这是 wpf 里的一个 bug,请告诉我你们对此的看法。
为了保持简单,我在 .net 4.0 中制作了演示示例。
我有一个 ContentControl,其中 Content 绑定到 Data,ContentTemplate 包含一个绑定到 Content 的 CheckBox。
问题是 Ok 属性无论我点击多少次 CheckBox 都不会变成 true。
就好像 CheckBox 没有将新值传递给 ViewModel。
看一下这个:
<Window.Resources>
<DataTemplate x:Key="dataTemplate">
<CheckBox IsChecked="{Binding Path=., Mode=TwoWay}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding Path=Ok, Mode=TwoWay}" ContentTemplate="{StaticResource dataTemplate}"/>
</Grid>
这是我的视图模型。
public MainWindow()
{
InitializeComponent();
ViewModel vm = new ViewModel();
this.DataContext = vm;
}
public class ViewModel : INotifyPropertyChanged
{
private string txt;
public string Txt
{
get { return txt; }
set { txt = value; this.OnPropertyChanged("Txt"); }
}
private bool ok;
public bool Ok
{
get { return ok; }
set { ok = value; this.OnPropertyChanged("Ok");}
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
有没有什么办法可以解决 ContentTemplate 的问题?
IsChecked="{Binding Path=.}"
被写成IsChecked="{Binding}"
将失败,因为双向绑定需要定义路径或xpath。然而,通过设置Path =.
,可以抑制验证/警告,导致出现这种行为。 - pushpraj