c# - 从 ViewModel 绑定 Observable Collection 到 View
问题描述
我已经尝试挖掘几个类似的帖子,并认为我错过了一些东西,因为我无法让我的数据出现。目前组合框是空的,我希望我在做一些愚蠢的事情并且错过了一些简单的事情。
模型
public class Rule
{
[Key]
public int RuleId { get; set; }
public string Rule { get; set; }
}
看法
<DataGridComboBoxColumn Header="Rule" DisplayMemberPath="Rule" Width="200">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=_ViewModel.Rules , RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=_ViewModel.Rules, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
查看续
public partial class RulePage : Page
{
private readonly RuleViewModel _ViewModel;
}
视图模型
public class RuleViewModel
{
public ObservableCollection<Rule> Rules { get; set; }
}
这是所有相关的代码,我相信。基本上我试图从页面的 _ViewModel 实例中获取规则列表以加载到组合框中,但它都是空白的。谢谢!
解决方案
幸运的是我自己解决了。原来因为这些是页面,我不得不{RelativeSource AncestorType={x:Type Window}
将{RelativeSource AncestorType={x:Type Page}
DataContext
导航时,我还必须将 设置为 Page 。
推荐阅读
- java - 在黄瓜java中的每个功能的钩子之后
- informatica - IICS Informatica - 不创建平面文件
- reactjs - 如何检查要使用反应组件参数调用的 ReactDOM.render 方法?
- c# - 通过虚拟工作室上的代码从右到左排序阅读的最佳方式是什么?
- r - R Shiny:即使更改条数,如何在 ggplot2 中保持条的宽度相同?
- node.js - cron.schedule 超出了我给定的时间范围?
- mysql - 将 NodeJS lambda 函数 (AWS) 转换为使用“异步”(承诺等)而不是回调
- julia - 使用 OpenStreetMapX 创建一个 powergrid 图网络
- azure - Pester 测试不会因数组缺失值而失败
- javascript - 有条件返回(无 if 或三元)