C# 将可观察集合从ViewModel绑定到视图
我试着翻阅了几篇类似的帖子,觉得我遗漏了一些东西,因为我无法显示我的数据。 现在组合框是空的,我希望我正在做一些愚蠢的事情,错过一些简单的事情 型号C# 将可观察集合从ViewModel绑定到视图,c#,wpf,mvvm,data-binding,datagrid,C#,Wpf,Mvvm,Data Binding,Datagrid,我试着翻阅了几篇类似的帖子,觉得我遗漏了一些东西,因为我无法显示我的数据。 现在组合框是空的,我希望我正在做一些愚蠢的事情,错过一些简单的事情 型号 public class Rule { [Key] public int RuleId { get; set; } public string Rule { get; set; } } public class RuleViewModel { public ObservableCollection<Rule&
public class Rule
{
[Key]
public int RuleId { get; set; }
public string Rule { get; set; }
}
public class RuleViewModel
{
public ObservableCollection<Rule> Rules { 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 class Rule
{
[Key]
public int RuleId { get; set; }
public string Rule { get; set; }
}
public class RuleViewModel
{
public ObservableCollection<Rule> Rules { get; set; }
}
公共类RuleViewModel
{
公共ObservableCollection规则{get;set;}
}
这是所有相关的代码,我相信。基本上,我试图从页面的_ViewModel实例中获取一个规则列表,以加载到combobox中,但其全部为空。谢谢 我自己幸运地解决了它。事实证明,由于这些是页面,我必须将
{RelativeSource-AncestorType={x:Type-Window}
设置为{RelativeSource-AncestorType={x:Type-Page}
每次导航时,我还必须将DataContext
设置到页面