WPF绑定将StaticResource返回为String

时间:2017-09-13 06:28:45

标签: wpf data-binding

我使用带有图像和标签的UserControl创建了一个自定义复选框。每当我点击它时,我想交换Checked和Unchecked图像。 到目前为止,我尝试了以下

<Image Source="{Binding StateImage}"/>

我有一个名为StateImage的属性

public String StateImage
{
     get
     {
         return is_checked?"{StaticResource Checked}":"StaticResource Unchecked";
     }
}

我的代码不起作用,我最终这样做了:

public String StateImage
    {
         get
         {
             return is_checked?"/Resources/Images/Checked.png":"/Resources/Images/Unchecked.png";
         }
    }

在UserControl的MouseDown事件

下修改is_checked变量

我是否可以更轻松地调用图像而无需编写整个路径和文件名?

1 个答案:

答案 0 :(得分:1)

您可以在strings

中将资源定义为UserControl
<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             xmlns:s="clr-namespace:System;assembly=mscorlib">
    <UserControl.Resources>
        <s:String x:Key="Checked">pic.png</s:String>
        <s:String x:Key="UnChecked"></s:String>
    </UserControl.Resources>
    <Grid Background="Yellow">
        <Image Source="{Binding StateImage}"/>
    </Grid>
</UserControl>
private bool is_checked;
public String StateImage
{
    get
    {
        return is_checked ? Resources["Checked"] as string : Resources["UnChecked"] as string;
    }
}
相关问题