WPF 映像更新



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

到目前为止,我拥有的代码如下。

<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>

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

我试过了 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 文档。

最新更新