WPF 图像更新

WPF Image update

我在使用 WPF 时遇到了一些问题,我想知道是否有人知道我接下来应该尝试什么。所以基本上我有一个处理 window,它绑定到一个字符串列表,每个字符串都在列​​表框中获取一个图像。

目前我拥有的代码如下。

<ListBox x:Name="MyListBox" ItemsSource="{Binding Items}"  Margin="36,100,320,100"  SelectedIndex="0" Panel.ZIndex="1" MouseDoubleClick="MyListBox_MouseDoubleClick">
        <ListBox.Resources>
            <BitmapImage x:Key="checkmark" UriSource="Images/checkmark.gif" />
            <BitmapImage x:Key="failure" UriSource="Images/red-x.gif" />
            <BitmapImage x:Key="processing" UriSource="Images/processing.gif" />
            <BitmapImage x:Key="white" UriSource="Images/white.gif" />
        </ListBox.Resources>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="{DynamicResource  white}" />
                    <TextBlock Text="{Binding}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我已尝试关注多篇在线文章,但我似乎无法将我的资源从白色更改为任何其他键。所以我想我的下一步是将动态资源指向一个 class 来确定每个对象的状态,但我似乎无法让它更新图像。

我试过了 MyListBox.SelectedItem = MyListBox.FindResource("checkmark"); MyListBox.InvalidateArrange(); MyListBox.UpdateLayout();

和其他一些人,但似乎没有太大作用。 我是 WPF 的新手,所以对于新手问题我深表歉意,但任何帮助或正确方向的推动都会非常有帮助。提前致谢。

您可以在 DataTemplate 上使用 DataTriggerTrigger 来更改图像源。如果您使用 DataTrigger 那么您将需要另一个 属性 来保存您要显示的图像的名称,以及要绑定的文本。例如:

        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <StackPanel.Resources>
                    <BitmapImage x:Key="checkmark" UriSource="Images/checkmark.gif" />
                    <BitmapImage x:Key="failure" UriSource="Images/red-x.gif" />
                    <BitmapImage x:Key="processing" UriSource="Images/processing.gif" />
                    <BitmapImage x:Key="white" UriSource="Images/white.gif" />
                </StackPanel.Resources>
                <Image x:Name="image" Source="{StaticResource  white}" />
                <TextBlock Text="{Binding Text}" />                    
            </StackPanel>
            <DataTemplate.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Source" TargetName="image" Value="{StaticResource checkmark}"/>
                </Trigger>
                <DataTrigger Binding="{Binding ImageToShow}" Value="failure">
                    <Setter Property="Source" TargetName="image" Value="{StaticResource failure}"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>

有关详细信息,请查看 MSDN doc