gpt4 book ai didi

wpf - 刷新使用值转换器的绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 13:43:21 25 4
gpt4 key购买 nike

我有一个绑定(bind)到对象的 WPF UI。我正在使用 ValueConverter 通过业务规则将属性转换为特定图像:

public class ProposalStateImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var proposal = value as Proposal;
var basePath = "pack://application:,,,/ePub.Content;component/Images/General/Flag_{0}.png";
string imagePath;

if(proposal.Invoice != null)
{
imagePath = string.Format(basePath, "Good");
}
else
{
imagePath = string.Format(basePath, "Warning");
}

var uri = new Uri(imagePath);
var src = uri.GetImageSource(); //Extention method

return src;
}
}

该元素是一个 TreeView,其中图像位于第二级:

<TreeView x:Name="tree"
ItemsSource="{Binding People}"
SelectedItemChanged="OnTreeItemChanged">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type dmn:Person}"
ItemsSource="{Binding Proposals}">
<StackPanel Orientation="Horizontal" ToolTip="{Binding Path=Fullname}" Margin="3">
<Image Margin="5,0,5,0" Width="16" Height="16" Source="pack://application:,,,/ePub.Content;component/Images/General/Person_Active.png" />
<TextBlock Text="{Binding Path=Firstname}" />
<TextBlock Text="{Binding Path=Lastname}" Margin="5,0,0,0" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type dmn:Proposal}">
<StackPanel Orientation="Horizontal" Margin="3">
<Image x:Name="invoiceImage" Width="16" Height="16" Margin="5,0,5,0" Source="{Binding, Converter={StaticResource ProposalStateImageConverter}, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{Binding DeliveryDate, Converter={StaticResource textCulturedDateConverter}}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>

它工作正常,但后来,当对象的状态发生变化时,我想刷新图像并使值转换器重新评估。这怎么可能?

最佳答案

看起来您只在转换器内部使用了一个值,而您只是在两个值之间进行了简单的切换,因此您可以直接在 XAML 中使用触发器执行此操作。此方法还切换到针对 Invoice 属性的绑定(bind),以便该属性的任何更改通知都会导致触发器更新。

<HierarchicalDataTemplate >
<StackPanel Orientation="Horizontal" Margin="3">
<Image x:Name="invoiceImage" Width="16" Height="16" Margin="5,0,5,0" Source="good.png"/>
<TextBlock ... />
</StackPanel>
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding Invoice}" Value="{x:Null}">
<Setter TargetName="invoiceImage" Property="Source" Value="warning.png"/>
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>

关于wpf - 刷新使用值转换器的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2469180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com