Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将可观察集合从ViewModel绑定到视图_C#_Wpf_Mvvm_Data Binding_Datagrid - Fatal编程技术网

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
设置到页面