2

这里有很大一部分问题,但通过进一步调查,我发现它无关紧要。

前言

我想Rectangle从代码隐藏中更改动态填充,所以我在资源字典中定义了画布(它是包 MahApps.Metro 中的 Icons.xml)并用这个图标应用于矩形填充。我只用矩形创建了空窗口:

<Window 
    x:Class="VKPlaylist.GUI.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" 
    Height="300" 
    Width="300"
>

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Resources/Icons.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid>
        <Rectangle Name="hurrdurr" HorizontalAlignment="Left" Height="190" Margin="53,37,0,0" VerticalAlignment="Top" Width="193">
            <Rectangle.Resources>
                <SolidColorBrush x:Key="BlackBrush" Color="Black" />
            </Rectangle.Resources>
            <Rectangle.Fill>
                <VisualBrush Stretch="Fill" Visual="{StaticResource appbar_settings}" />
            </Rectangle.Fill>
        </Rectangle>
    </Grid>
</Window>

Icons.xml 条目如下所示:

<Canvas Width="48" Height="48" Clip="F1 M 0,0L 48,0L 48,48L 0,48L 0,0" x:Key="appbar_add">
        <Path Width="24" Height="24" Canvas.Left="12" Canvas.Top="12" Stretch="Fill" Fill="{DynamicResource BlackBrush}" Data="F1 M 22,12L 26,12L 26,22L 36,22L 36,26L 26,26L 26,36L 22,36L 22,26L 12,26L 12,22L 22,22L 22,12 Z " />
    </Canvas>

问题

从代码隐藏进行两到三个交换后图标消失。我使用了这个测试:

public partial class Window1
{
    public Window1()
    {
        InitializeComponent();
        this.Loaded += (sender, args) => 
            new Thread(() => {
                Dispatcher.Invoke(new Action(() => hurrdurr.Fill = new VisualBrush(ResourceProvider.GetIcon("appbar_pause"))));
                Thread.Sleep(1000);
                Dispatcher.Invoke(new Action(() => hurrdurr.Fill = new VisualBrush(ResourceProvider.GetIcon("appbar_play"))));
                Thread.Sleep(1000);
                Dispatcher.Invoke(new Action(() => hurrdurr.Fill = new VisualBrush(ResourceProvider.GetIcon("appbar_pause")))); // rectangle became blank on this iteration
                Thread.Sleep(1000);
                Dispatcher.Invoke(new Action(() => hurrdurr.Fill = new VisualBrush(ResourceProvider.GetIcon("appbar_play"))));
            }).Start();
    }
}

internal static class ResourceProvider
{
    private static ResourceDictionary Icons;

    public static Canvas GetIcon(string key)
    {
        if (Icons == null)
        {
            Icons = new ResourceDictionary();
            Icons.Source = new Uri("pack://application:,,,/VKPlaylist;component/Resources/Icons.xaml");
        }
        return Icons.Contains(key) ? Icons[key] as Canvas : null;
    }
}

对我来说它看起来像一个错误,但我不知道这是 WPF 的错误还是它是Fill="{DynamicResource BlackBrush}"来自 MahApps.Metro 的 Icons.xml 操作的结果。

4

0 回答 0