首页 > 解决方案 > MVVM 绑定到数组索引

问题描述

我正在使用 MVVM,并且正在尝试绑定数组索引。XAML 控件的数据上下文绑定到视图模型。当我实例化控件时,我将数组索引发送到构造函数,然后将该索引分配给窗口资源,以便 XAML 可以直接使用它。该值按预期传递给构造函数,我可以在 XAML 页面的其他区域使用它,但由于某种原因,它不能用作数组索引。有谁知道这里发生了什么?

C#:

public partial class MyControl : UserControl {

    public MyControl(int index) {
        MyIndex = index;
        InitializeComponent();
    }

    private int myIndex;
    public int MyIndex {
        get { return myIndex; }
        set { myIndex = value; }
    }

    private void Mygrid_OnLoaded(object sender, System.Windows.RoutedEventArgs e) {
        Resources["myResourceKey"] = MyIndex;
    }
} 

这是xaml:

定义资源:

<UserControl.Resources>
    <sys:Int32 x:Key="myResourceKey"></sys:Int32>
</UserControl.Resources>

这不起作用。我收到绑定错误,因为它无法识别索引

 <GradientStop Color="{Binding MyObservableCollection[DynamicResource myResourceKey].ColorsBo.PageBackgroundPrimary}" Offset="1"/>

这确实有效,因此资源值被传递到 xaml:

<Label Grid.Column="0" Content="{DynamicResource myResourceKey}"/>

标签: c#wpfxamlmvvmbinding

解决方案


以下 XAML 无效:

MyObservableCollection[DynamicResource myResourceKey]

DynamicResource myResourceKey必须用常量替换,例如1'abc'

另一种选择是按照@Martin Zikmund 的建议在视图模型中执行查找,或者使用绑定到和多转换器的多绑定myResourceKeyMyObservableCollectionhttps: //blog.csainty.com/2009/12/wpf-multibinding -and.html


推荐阅读