首页 > 解决方案 > 从 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 实例中获取规则列表以加载到组合框中,但它都是空白的。谢谢!

标签: c#wpfmvvmdata-bindingdatagrid

解决方案


幸运的是我自己解决了。原来因为这些是页面,我不得不{RelativeSource AncestorType={x:Type Window}{RelativeSource AncestorType={x:Type Page}

DataContext导航时,我还必须将 设置为 Page 。


推荐阅读