WPF use binding to assign static resource

前端 未结 2 1315
一向
一向 2021-02-12 13:16

I am trying to use an enum to display a corresponding image. For this I have a value converter that converts an enum to the correct resource name. My resources are defined as fo

相关标签:
2条回答
  • 2021-02-12 13:25

    You cannot bind the StaticResource Key as it is not the DependancyProperty. Either you will have to Bind Source directly to the enum using converter and update the converter code to return the Bitmap itself.

    Second option will be to used Triggers to set the Source property depending on the enum value.

    <Image >
       <Image.Style>
          <Style TargetType="{x:Type Image}">
             <Style.Triggers>
                <DataTrigger Binding="{Binding CurrentAlarmItem.AlarmCategory}" 
                             Value="Category1">
                   <Setter Property="Source" Value="{StaticResource AlarmCat1}" />
                </DataTrigger>
             </Style.Triggers>
          </Style>
       </Image.Style>
    </Image>
    
    0 讨论(0)
  • 2021-02-12 13:40

    I would return the resource in the converter:

    <Image Source="{Binding CurrentAlarmItem.AlarmCategory, Converter={StaticResource AlarmCategoryConverter}}" />
    

    In your converter do something like this:

    return Application.Current.FindResource("AlarmCat1") as BitmapImage;
    

    Set your resources for the complete application with the use of resourcedictionary (app.xaml)

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    

    In your Dictionary (Dictionary1.xaml)

    <BitmapImage x:Key="AlarmCat1" UriSource="bh.jpg" />
    

    Because your resources are now defined on applicationlevel, the code will now find your resource and give it back.

    0 讨论(0)
提交回复
热议问题