2014-04-22 193 views
0

我已经绑定了ObservableCollection到ItemSource到DataGrid,但是,我想通过ViewModel检索(通过setter)单个属性。WPF绑定属性到Datagrid

好听起来令人困惑,所以会解释。在我的ObservableCollection中,我有一个名为“Active”的属性,所以我想在用户点击或关闭DataGrid中的复选框时设置该元素。

所以XAML

<DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
     <CheckBox IsChecked="{Binding Active, Mode=TwoWay}" HorizontalAlignment="Center"></CheckBox> 
    </DataTemplate> 
</DataGridTemplateColumn.CellTemplate> 

而且我想,当没有选中该复选框这触发视图模型的代码或检查

private bool m_Active = false; 

public bool Active 
{ 
    get { return m_Active; } 
    set 
    { 
     m_Active = value; 

     OnPropertyChanged("Active"); 
    } 
} 

但即使双向模式上,这不是”吨。任何原因为什么?

注意:在DataGrid的SelectedItem属性中,我可以得到SelectedRow,所以基本上我想要选择Individual属性!

感谢

+0

datacontext是不同的。复选框的datacontext将是行项目,但您的属性在您的视图模型中。 – Shoe

+0

我明白,这意味着我只能从设置DataContext的行项目中获取单个属性? – user3428422

回答

0

这听起来像你混淆了在数据网格中寻找“活跃”属性。由于datagrid绑定到Observable集合,因此observable集合中的对象需要具有“Active”属性,而不是用于视图的视图模型。但是,如果实际上想要将数据网格的所有行绑定到视图模型上的单个属性,则需要查找祖先树来查找控件的数据上下文,然后绑定到“活动”属性:

<CheckBox IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.Active, Mode=TwoWay}" HorizontalAlignment="Center"></CheckBox> 

但是,我想,你正在寻找绑定到可观察集合中对象的'Active'属性。在运行应用程序时检查输出窗口,如果该对象上不存在该属性,则应该看到绑定错误。

+0

嗨乔希,主动财产是Observable集合的财产。我只需要做一些用户是否想要检查它的逻辑。所以我的理解是,selectedItem将从Observable集合中选择一行,其中包含所有的属性。这是伟大的,但我现在只需要知道,如果用户正在检查活动的属性或不 – user3428422

0

尝试使用CellEditingTemplate

<DataGridTemplateColumn.CellEditingTemplate> 
       <DataTemplate> 
        <CheckBox IsChecked="{Binding Active, Mode=TwoWay}" HorizontalAlignment="Center"></CheckBox> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellEditingTemplate> 

希望帮助

0

你试过设置UpdateSourceTrigger?

<CheckBox IsChecked="{Binding Active, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center"></CheckBox> 
+0

我有,谢谢,但我想我需要使用relativeSource绑定 – user3428422