WPF按键绑定到字典中的项目
WPF Binding to items within a dictionary by key
我希望它将 TextBoxes 绑定到我的字典值。
我已经可以找到一些关于它的帖子但是:
一个表示将我的字典作为上下文:
XML :
<TextBox x:Name="FirstLine" Text="{Binding Path=[FirstLine]}"/>
XAML :
public ImportProfilesOptions()
{
InitializeComponent();
contexte = new ViewModelImportProfilesOptions();
DataContext = contexte.ParamsData;
}
另一个using Templates :
<ItemsControl x:Name="dictionaryItemsControl" ItemsSource="{Binding dictionary}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但我想使用它,而不使用模板(我需要在标签中添加一些我从属性中获取的翻译),并且不将我的字典设置为上下文。类似的东西:
XML
<TextBox x:Name="FirstLine" Text="{Binding Path=ParamsDate[FirstLine]}" />
XAML
contexte = new ViewModelImportProfilesOptions();
DataContext = contexte;
但是,绑定不再起作用了。
你不能开箱即用,但我想你可以创建自己的转换器:
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();
}
用法
<TextBlock Text="{Binding Path=ParamsDate,
ElementName=TextBox,
Converter={StaticResource SomeFunkyConverter},
ConverterParameter='Bob'}"/>
注意:完全未经测试
我希望它将 TextBoxes 绑定到我的字典值。 我已经可以找到一些关于它的帖子但是:
一个表示将我的字典作为上下文:
XML :
<TextBox x:Name="FirstLine" Text="{Binding Path=[FirstLine]}"/>
XAML :
public ImportProfilesOptions()
{
InitializeComponent();
contexte = new ViewModelImportProfilesOptions();
DataContext = contexte.ParamsData;
}
另一个using Templates :
<ItemsControl x:Name="dictionaryItemsControl" ItemsSource="{Binding dictionary}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但我想使用它,而不使用模板(我需要在标签中添加一些我从属性中获取的翻译),并且不将我的字典设置为上下文。类似的东西:
XML
<TextBox x:Name="FirstLine" Text="{Binding Path=ParamsDate[FirstLine]}" />
XAML
contexte = new ViewModelImportProfilesOptions();
DataContext = contexte;
但是,绑定不再起作用了。
你不能开箱即用,但我想你可以创建自己的转换器:
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();
}
用法
<TextBlock Text="{Binding Path=ParamsDate,
ElementName=TextBox,
Converter={StaticResource SomeFunkyConverter},
ConverterParameter='Bob'}"/>
注意:完全未经测试