在DataGridTemplateColumn DataTemplate中, 我想将2个控件绑定到格式为“[name]:[value]”的字符串字段,即字符串由冒号“:”分隔。我需要将控件a)绑定到[name]部分并控制b)值部分。
我已成功使用IValueConverter拆分显示字符串:
public class NameAndValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string rtn = "";
string[] split = value.ToString().Split(':');
if (split.Count() == 2)
{
if(parameter.ToString() == "Name")
rtn = split[0];
if(parameter.ToString() == "Value")
rtn = split[1];
}
return rtn;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("NameAndValueConverter can only be used OneWay.");
}
}
和XAML:
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<local:NameAndValueConverter x:Key="NameAndValueConverter" />
</StackPanel.Resources>
<TextBox x:Name="namePart" Text="{Binding Path=FieldType, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Name'}" />
<TextBox x:Name="valuePart" Text="{Binding Path=FieldType, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Value'}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
但是可以在文本框中编辑数据,那么如何在ConvertBack中访问2个TextBox值以便它们可以再次连接?
答案 0 :(得分:1)
在XAML中执行此操作:
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<local:NameAndValueConverter x:Key="NameAndValueConverter" />
</StackPanel.Resources>
<TextBox x:Name="namePart" Text="{Binding Path=FieldType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Name'}" />
<TextBox x:Name="valuePart" Text="{Binding Path=FieldType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Value'}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
应该足够了。您需要TwoWay
绑定才能在UI中进行修改,当您将UpdateSourceTrigger
设置为PropertyChanged
时,TextBox
会在ViewModel中修改属性时自动更新自身(您显然需要实施INotifyPropertyChanged
)