我在视图中有一个文本框。如果我在文本框A中输入一个值,那么文本块B的值将自动显示。这两个属性之间的关系是在ViewModel的字典中定义的。
Dictionary<string,string> dict = LoadFromDb();
// dict["01"] = "USA";
// dict["02"] = "ENG";
// If I input 01 in code textbox, then the country textblockwill display USA.
文本框和文本块位于单元模板中。让我给你举个例子。
<telerik:RadGridView Name="radGridView1" ShowGroupPanel="False" ShowGroupFooters="False" AutoGenerateColumns="False" ItemsSource="{Binding Persons}">
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn Header="Code" DataMemberBinding="{Binding Code}">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Code}" />
</StackPanel>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
<telerik:GridViewDataColumn Header="Country" DataMemberBinding="{Binding Country}">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Country}" />
</StackPanel>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
</telerik:RadGridView.GridViewDataColumns>
我无法将它们绑定到模型类中,因为模型类没有字典的信息。
那么最好的方法是什么?
答案 0 :(得分:2)
将“国家/地区”列绑定到整个数据条目,并使用转换器显示只读值:如果它来自数据库-未经修改,否则-从字典中获取它。
<Window.Resources>
<local:ValueConverter x:Key="convResName"/>
</Window.Resources>
...
<telerik:GridViewDataColumn Header="Country" DataMemberBinding="{Binding}">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Converter={StaticResource convResName}, ConverterParameter={StaticResource {x:Static local:YourViewModel.yourDictAsStaticProperty}}}" />
</StackPanel>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
public class ValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var person = value as Person;
if (person==null)
{
return null;
}
var dict = parameter as Dictionary<string, string>;
if (string.IsNullOrWhiteSpace(person.Country))
{
try
{
person.Country = dict[person.Code];
}
catch (KeyNotFoundException exc)
{
//handle exc
}
}
return person.Country;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}