【问题标题】:Binding Observable Collection from ViewModel to View从 ViewModel 绑定 Observable Collection 到 View
【发布时间】:2020-06-22 23:38:30
【问题描述】:

我已经尝试挖掘了几篇类似的帖子,并认为我遗漏了一些东西,因为我无法让我的数据出现。 目前组合框是空的,我希望我在做一些愚蠢的事情并且错过了一些简单的事情。

型号

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# wpf mvvm data-binding datagrid


    【解决方案1】:

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

    我还必须在导航时将DataContext 设置为页面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多