简体   繁体   English

WPF 按键绑定到字典中的项目

[英]WPF Binding to items within a dictionary by key

What I want it to bind TextBoxes to my dictionaries values.我希望它将 TextBoxes 绑定到我的字典值。 I could find some posts about it already but:我已经可以找到一些关于它的帖子,但是:

One means having my dictionary as context:一种意味着将我的字典作为上下文:

XML: XML:

<TextBox x:Name="FirstLine" Text="{Binding Path=[FirstLine]}"/>

XAML: XAML:

public ImportProfilesOptions()
{
    InitializeComponent();
    contexte = new ViewModelImportProfilesOptions();
    DataContext = contexte.ParamsData;

}

The other one using Templates :另一个使用模板

<ItemsControl x:Name="dictionaryItemsControl" ItemsSource="{Binding dictionary}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Key}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

But I would like to use it, without using Templates (I need to add in labels some translates I take from properties), and without setting my dictionary as context.但是我想使用它,而不使用模板(我需要在标签中添加一些我从属性中获取的翻译),并且不将我的字典设置为上下文。 Something like that:像这样的东西:

XML XML

<TextBox x:Name="FirstLine" Text="{Binding Path=ParamsDate[FirstLine]}" />

XAML XAML

contexte = new ViewModelImportProfilesOptions();
DataContext = contexte;

But then, binding is not working anymore.但是,绑定不再起作用。

You can't do this out of the box, though you could create your own converter I guess:你不能开箱即用,但我猜你可以创建自己的转换器:

public class SomeFunkyConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      if (!(value is Dictionary<string,string> dictionary))
         return null;

      if (!(parameter is string key))
         return null;

      return !dictionary.TryGetValue(key, out var result) ? null : result;
   }
   
   // ill leave this up to you
   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    => throw new NotSupportedException();
}

Usage用法

<TextBlock Text="{Binding Path=ParamsDate, 
                          ElementName=TextBox, 
                          Converter={StaticResource SomeFunkyConverter},
                          ConverterParameter='Bob'}"/>

Note : Completely untested注意:完全未经测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM