【问题标题】:Bind WPF DataGridComboBoxColumn to custom source将 WPF DataGridComboBoxColumn 绑定到自定义源
【发布时间】:2011-09-05 08:17:42
【问题描述】:

我绑定了一个 View 和 ViewModel (WPF/C#)。

现在,在DataGrid 中有一个DataGridComboBoxColumn,我想将组合的ItemsSource 设置为ViewModel 的某个固定属性。不幸的是,组合的隐式数据上下文是当前行。

我要做的就是从当前行的 DataContext 中“跳出”。

感谢您的任何回答..

【问题讨论】:

    标签: c# .net wpf data-binding datagrid


    【解决方案1】:

    例如在我的项目中,我通过以下方式将组合框绑定到 ViewModel 的属性

    <ComboBox Name="projectcomboBox" ItemsSource="{Binding Path=Projects}" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="FullName"
                  SelectedValuePath="Name"  SelectedIndex="0"  Grid.Row="1" Visibility="Visible" Canvas.Left="10" Canvas.Top="24" Margin="11,6,13,10">
        </ComboBox>
    

    属性是

     public ObservableCollection<Project> Projects
        {
            get { return projects; }
            set
            {
                projects = value;
                RaisePropertyChanged("Projects");
            }
        }
    

    设置 ItemsSource、DisplayMemberPath、SelectedValuePath 属性很重要。 SelectedIndex 你也可以绑定

    【讨论】:

    • 不幸的是,关键问题是其他问题,DataContext 与绑定本身无关。
    【解决方案2】:

    我所做的是将窗口设置为拥有 ViewModel 的 DataContext 然后执行以下操作:

    <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=NodeNames}">
    </ComboBox>
    

    这会在树中找到窗口,然后为我绑定到一个名为 NodeNames 的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2017-06-25
      • 2015-11-24
      相关资源
      最近更新 更多