基于属性值与DrawingImage绑定的图像源

时间:2018-04-25 08:50:38

标签: c# wpf xaml data-binding

我已在存储库文件中声明了DrawingImage数据,如下所述。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:DynamicImageSourceFromResourceDIctionary">
    <DrawingImage x:Key="low">
        <DrawingImage.Drawing>
            <GeometryDrawing Geometry="M4.5,84.6l224.9,374.8c12.1,20.1,41.2,20.1,53.3,0L507.5,84.6c12.4-20.7-2.5-47.1-26.7-47.1H31.1
            C7,37.5-8,63.9,4.5,84.6z" Brush="#003854">
            </GeometryDrawing>
        </DrawingImage.Drawing>
    </DrawingImage>

    <DrawingImage x:Key="high">
        <DrawingImage.Drawing>
            <GeometryDrawing Geometry="M507.521,427.394L282.655,52.617c-12.074-20.122-41.237-20.122-53.311,0L4.479,427.394    c-12.433,20.72,2.493,47.08,26.655,47.08h449.732C505.029,474.474,519.955,448.114,507.521,427.394z" Brush="#003854">
            </GeometryDrawing>
        </DrawingImage.Drawing>
    </DrawingImage>
</ResourceDictionary>

- &GT;现在在主窗口中有一个图像和两个按钮

<Grid>
        <Image x:Name="image" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Source="{Binding ImgSource}"/>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="36,137,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
        <Button x:Name="button_Copy" Content="Button" HorizontalAlignment="Left" Margin="137,136,0,0" VerticalAlignment="Top" Width="75" Click="button_Copy_Click"/>
    </Grid>

- &GT; MainWindow类文件中有一个字符串属性。

    private string _imgSource;
    public string ImgSource
    {
        get { return _imgSource; }
        set { _imgSource = value; OnPropertyChanged("ImgSource"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propname)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propname));
        }
    }

- &GT;单击按钮,我将值分配给ImgSource属性。

private void button_Click(object sender, RoutedEventArgs e)
        {
            ImgSource = "low";
        }

        private void button_Copy_Click(object sender, RoutedEventArgs e)
        {
            ImgSource = "high";
        }

- &GT;现在我想将绘图图像设置为

如果ImgSource =“low”则在窗口中定义Image,应设置资源字典中定义的箭头

1 个答案:

答案 0 :(得分:0)

从字符串到ImageSource的内置自动类型转换对于DrawingImage资源并不神奇。

将ImgSource属性的类型从字符串更改为ImageSource

public ImageSource ImgSource
{
    get { return _imgSource; }
    set { _imgSource = value; OnPropertyChanged("ImgSource"); }
}

并手动查找资源:

ImgSource = Application.Current.FindResource("low") as ImageSource;