wpf - DataGrid 的 C# wpf TwoWay 动态绑定(DataGridCheckColumn 和 DataGridTextColumn)
问题描述
目标
CheckBoxColumn TwoWay 绑定,用于访问用户输入。
问题描述
1. 空表(所以找不到对象实例)
2. MVVM 怎么知道要使用对象的哪个实例?是否有任何调试/帮助选项可用于正确键入?
.xaml
<DataGrid x:Name="bGrid" ItemsSource="{Binding
Source=window.obColl_B,
UpdateSourceTrigger=PropertyChanged, Mode=TwoWay,
Path=BindsDirectlyToSource}" >
<DataGrid.Columns>
<DataGridCheckBoxColumn Width="0.25*" Header="Check"
Binding="{Binding berCheck}" IsReadOnly="False" />
<DataGridTextColumn Width="0.5*" Header="Beruf"
Binding="{Binding berName}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
C#
public class obsColl : ObservableCollection<bEntry>
{
public obsColl(List<string> berList, List<string> bActive) : base()
{
for (int i = 0; i < berList.Count; i++)
{
if (bActive.Contains(berList[i]))
Add(new bEntry(true, berList[i]));
else
Add(new bEntry(false, berList[i]));
}
}
}
public class bEntry
{
private bool _berCheck;
private string _berName;
public bEntry(bool check, string name)
{
this._berCheck = check;
this._berName = name;
}
public bool berCheck
{
get { return _berCheck; }
set { _berCheck = value; }
}
public string berName
{
get { return _berName; }
set { _berName = value; }
}
}
public partial class window : Window
{
obsColl obColl_B;
public AuswahlBerufWindow(List<string> berList, List<string> berActive)
{
obColl_B = new obsColl(cpy_berList, cpy_berActive);
//so how does MVVM find the correct object to bind?
InitializeComponent();
...
}
}
// obColl_B automatically changes due to user input
据我了解。ObservableCollection 为我处理 IPropertyChanged 和 INotifyChanged,因此我应该能够使用 Mode=TwoWay 将其与用户输入绑定。然而,即使是单个绑定也会失败。我确实使用的想法来自 https://blogs.u2u.be/diederik/post/Codeless-two-way-data-binding-to-a-WPF-DataGrid
但是我不太明白的是如何为 MVVM 分配正确的元素以供使用。大多数示例确实使用静态输入,这无济于事。从我读到的内容来看,我需要提供相应类型的 .xaml 解释器对象(ObservableCollection),但我不知道如何通过 Mode=TwoWay 取回这些值。
我尝试了另一种在没有绑定的情况下手动编写 DataTable 的方法,但是这种方式(仅定义类型、标题和只读)只添加了复选框的数量而没有添加内容。有趣的是,它并没有因异常而失败。
更新 1
错误 1. 绑定错误/程序因“此视图不允许 EditItem”而失败,如果Path+Mode+UpdateSourceTrigger未设置,则可能已修复。然而,这看起来“固定”。
更新 2
错误应该在于不正确的对象源。
解决方案
在您的 ViewModel 中,您必须引入 ObservableCollection 类型的属性。
在您的 XAML 中,您必须将 Datacontext 设置为整个 ViewModel 或仅设置为属性。
将 MainViewModel 绑定到 MainWindow.xaml 的示例
DataContext="{Binding Main, Source={StaticResource Locator}
MVVM 知道要使用什么,因为 ViewModelLocator
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
我建议使用 MVVM Light。MVVM Light 为您提供了非常好的 MVVM 模式的基本实现。
推荐阅读
- sql - 如何组合来自 SQL 查询的结果
- reactjs - 类型错误:_firebase__WEBPACK_IMPORTED_MODULE_4__.default.auth 不是函数
- javascript - 隐藏基于单选的问题集
- data-structures - 数据结构:什么是固定大小的数组与称为(双重)链表的组合?
- c++ - 指针初始化错误导致写访问冲突
- spring-amqp - 不可能(?) NullPointerException - Springframework RabbitMQ,无法调用 afterAckCallback
- python - 如何在python中查找两个数字是否变化一定数量?
- php - 带图片上传的 PHP 表单
- sql - 从 postgresql 中的 2 个单独的表中复制数据
- javascript - 使用静态链接实现 oEmbed 发现