【问题标题】:WPF, Binding Programmatically an item of a Observable collection of listWPF,以编程方式绑定列表的可观察集合的项目
【发布时间】:2016-11-30 10:34:18
【问题描述】:

我有一个ObservableCollection<List<MessageView>>(MessageView 是一个自定义类)我以这种方式实例化它

public ObservableCollection<List<MessageView>> _messagesView;
public ObservableCollection<List<MessageView>> messagesView {
    get {
        if (_messagesView == null) {
            _messagesView = new ObservableCollection<List<MessageView>>();
        }
        return _messagesView;
    }
    set {
        if (_messagesView != value) {
            _messagesView = value;
            PropertyChanged(this, new PropertyChangedEventArgs(nameof(messagesView)));
        }
    }
}

这个属性是在单例上设置的

我想将其中一个项目集合绑定到一个数据网格,它在 xaml 中看起来是这样的:

<xmlns:module="clr-namespace:Myproject.MyNameSpace;assembly=Myproject">
<DataGrid 
    Name="DataGrid_messages"
    ...
    ItemsSource="{Binding messagesView[2], Source={x:Static module:Singleton.Instance}}"
>

这种方式效果很好,但这不是我想要做的。我想控制我的索引。所以我必须用我的控制器在 c# 中进行绑定,但我从来没有找到一个使用特殊索引绑定的示例。

Binding myBinding = new Binding("messagesView");
myBinding.Source = Singleton.Instance;
myBinding.Path = ??
DataGrid_messages.SetBinding(DataGrid.ItemsSourceProperty, myBinding);

分享你的想法,这可能吗?还是有更好的方法?

更新

与 Clemens 答案有关的其他更改:

绑定是使用内部列表设置的,所以它应该是 ObservableCollection 类型:

public List<ObservableCollection<MessageView>> messagesView;

【问题讨论】:

  • 如果索引是固定的,myBinding.Path = new PropertyPath(string.Format("messagesView[{0}]", index)); 应该可以工作。
  • @Clemens 我明白了。感谢您的信息。
  • @Clemens 谢谢它运行良好!但是现在我每次更改属性 An ItemsControl is inconsistent with its items source 时都会出现异常情况
  • UpdateSourceTrigger=PropertyChanged 对单向绑定没有影响,并且与 ItemsControl 的 ItemsSource 属性的绑定始终是单向的。
  • @Clemens Hum 好吧,但添加 myBinding.Mode = BindingMode.OneWay; 不应该这样吗?

标签: c# wpf xaml datagrid


【解决方案1】:

假设索引是固定的,在后面的代码中创建绑定路径可能如下所示:

myBinding.Path = new PropertyPath(string.Format("messagesView[{0}]", index)); 

【讨论】:

    猜你喜欢
    • 2023-02-14
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2015-10-21
    • 2015-03-07
    • 1970-01-01
    • 2021-12-15
    • 2020-12-29
    相关资源
    最近更新 更多