绑定内部绑定 WPF

Binding inside binding WPF

我有一个项目字典,我想在组合框中显示项目的一个方面 - 全部采用 MVVM 模式。对此,我定义我的Model为:

public class Model
{
    public Dictionary<UInt32, string> samples { set; get; }
}

和我的 ViewModel 作为:

internal class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        var smpls = new Dictionary<UInt32, string>();
        smpls.Add(1, "one");
        smpls.Add(2, "two");
        models = new Dictionary<string, Model>();
        models.Add("aKey", new Model() { samples = smpls });

        key = "aKey";
    }

    private Dictionary<string, Model> _models;
    public Dictionary<string, Model> models { set { _models = value; } get { return _models; } }

    private string _key;
    public string key { set { _key = value; OnPropertyChanged("key"); } get { return _key; } }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

然后我将 models 绑定到组合框,如下所示:

<Grid>
    <ComboBox ItemsSource="{Binding Path=models[{Binding Path=key}].samples, Mode=OneTime}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Border>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Value}" />
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</Grid>

我正在将 models 字典的键绑定到 viewModelkey 属性,但这不起作用。但是,如果我按照以下方式更改代码,一切正常:

<ComboBox ItemsSource="{Binding Path=models[aKey].samples, Mode=OneTime}">

虽然 models[aKey].samples 是一个有效的 property path, models[{Binding Path=key}].samples isn't. You might probably get around this limitation by using a MultiBinding,具有适当的值转换器。

然而,创建一个额外的视图模型 属性 会容易得多,例如下面显示的 CurrentSamples 属性,只要 key [=23] 就会更新=] 变化:

public Dictionary<UInt32, string> CurrentSamples
{
    get { return models[key].samples; }
}

public string key
{
    get { return _key; }
    set
    {
        _key = value;
        OnPropertyChanged("key");
        OnPropertyChanged("CurrentSamples");
    }
}

然后像这样绑定 ItemsSource:

<ComboBox ItemsSource="{Binding CurrentSamples}">
    ...
</ComboBox>

I'm binding the Key of models dictionary to key property of viewModel which does not work.

绑定通过反映到 CLR 结构中来工作。它通常使用 Path 属性中的文字在 CLR 实例上查找 属性。 models[{Binding Path=key}] 不是结构的正确 路径

它没有被编程为在绑定中搜索绑定;它将文本作为 path.

的文字

To quote MSDN Binding Sources Overview: For CLR properties, data binding works as long as the binding engine is able to access the binding source property using reflection.

所以第二个绑定 (Path=models[aKey].samples) 有效,因为您提供了一个真正的 pathed 位置来反映和绑定到。