wpf 4.0 datagrid模板列双向绑定问题 [英] wpf 4.0 datagrid template column two-way binding problem
问题描述
我正在使用 wpf 4.0 中的数据网格.它有一个包含复选框的 TemplateColumn.复选框的 IsChecked 属性是通过绑定设置的.
I'm using the datagrid from wpf 4.0. This has a TemplateColumn containing a checkbox. The IsChecked property of the checkbox is set via binding.
问题是,即使我明确指定绑定模式为 TwoWay,它也只能在一个方向上工作.
The problem is that even if I specify the binding mode explicitly to be TwoWay, it works only in one direction.
我不得不提一下,相同的代码在 .net 3.5 中与 wpf 工具包中的数据网格完美结合.
I have to mention that the same code works perfectly in .net 3.5 with the datagrid from the wpf toolkit.
请查看 .xaml 和 .cs 内容.
Please take a look at the .xaml and .cs contents.
提前致谢,
罗兰
<Window.Resources>
<DataTemplate
x:Key="IsSelectedColumnTemplate">
<CheckBox
IsChecked="{Binding Path=IsSelected, Mode=TwoWay}"
/>
</DataTemplate>
</Window.Resources>
<Grid>
<DataGrid
x:Name="dataGrid"
AutoGenerateColumns="false"
CanUserAddRows="False"
CanUserDeleteRows="False"
HeadersVisibility="Column"
ItemsSource="{Binding}"
>
<DataGrid.Columns>
<DataGridTemplateColumn
Header="Preselected"
x:Name="myIsSelectedColumn"
CellTemplate="{StaticResource IsSelectedColumnTemplate}"
CanUserSort="True"
SortMemberPath="Orientation"
Width="Auto"
/>
</DataGrid.Columns>
</DataGrid>
</Grid>
以及相关的 .cs 内容:
and the related .cs content:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ObservableCollection<DataObject> DataSource = new ObservableCollection<DataObject>();
DataSource.Add(new DataObject());
DataSource.Add(new DataObject());
dataGrid.ItemsSource = DataSource;
}
}
public class DataObject : DependencyObject
{
public bool IsSelected
{
get { return (bool)GetValue(IsSelectedProperty); }
set { SetValue(IsSelectedProperty, value); }
}
// Using a DependencyProperty as the backing store for IsSelected. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsSelectedProperty =
DependencyProperty.Register("IsSelected", typeof(bool), typeof(DataObject), new UIPropertyMetadata(false, OnIsSelectedChanged));
private static void OnIsSelectedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
// this part is not reached
}
}
推荐答案
您在数据模板的 Checkbox IsChecked 绑定中设置 UpdateSourceTrigger=PropertyChanged:<代码><复选框IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
You set UpdateSourceTrigger=PropertyChanged in your Checkbox IsChecked binding in the datatemplate:
<CheckBox
IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
/>
这篇关于wpf 4.0 datagrid模板列双向绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!