题
当记录更改时,我需要在我的ListView中显示旧值和新值。我的意思是每个单元格都应显示新的值和旧值。现在我这样做:
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding MyValue}"/>
<TextBlock Margin="7,0,0,0" Text="{Binding old.MyValue}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
对于下一列将是:
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding MySecondValue}"/>
<TextBlock Margin="7,0,0,0" Text="{Binding old.MySecondValue}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
但是我有10列,这并不有趣,可以为所有10列制作大量复制。
有什么想法如何更紧凑,更好?
我想要的理想变体就是这样:
<GridViewColumn.CellTemplate>
<DataTemplate>
<MySpecialWhatever NewValueText="{Binding MyValue}" OldValueText="{Binding old.MyValue}" >
</MySpecialWhatever>
</DataTemplate>
</GridViewColumn.CellTemplate>
解决方案
您可以通过这样的自定义USERCORTROL实现目标。
DoubleValuesCell.XAML
<UserControl x:Class="WpfApplication1.DoubleValuesCell"
x:Name="root"
...>
<StackPanel>
<TextBlock Text="{Binding NewValue, ElementName=root}"/>
<TextBlock Margin="7,0,0,0" Text="{Binding OldValue, ElementName=root}"/>
</StackPanel>
</UserControl>
DoubleValuescell.xaml.cs
public partial class DoubleValuesCell : UserControl
{
public static readonly DependencyProperty NewValueProperty = DependencyProperty.Register("NewValue", typeof(object), typeof(DoubleValuesCell));
public static readonly DependencyProperty OldValueProperty = DependencyProperty.Register("OldValue", typeof(object), typeof(DoubleValuesCell));
public object NewValue
{
get { return GetValue(NewValueProperty); }
set { SetValue(NewValueProperty, value); }
}
public object OldValue
{
get { return GetValue(OldValueProperty); }
set { SetValue(OldValueProperty, value); }
}
public DoubleValuesCell()
{
InitializeComponent();
}
}
xxxwindow.xaml
<Window x:Class="WpfApplication1.XXXWindow"
xmlns:local="clr-namespace:WpfApplication1"
...>
...
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<local:DoubleValuesCell NewValue="{Binding MyValue}" OldValue="{Binding old.MyValue}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
...
</Window>
更新
您可以使用DataTrigger折叠第二个控件。
<StackPanel>
<TextBlock Text="{Binding NewValue, ElementName=root}"/>
<TextBlock Margin="7,0,0,0" Text="{Binding OldValue, ElementName=root}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding OldValue, ElementName=root}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
上面的代码意味着如果绑定源值(OldValue属性)为null,则第二个文本块折叠。
不隶属于 StackOverflow