如何在视图模型中绑定静态资源键

本文关键字:绑定 静态 资源 模型 视图 | 更新日期: 2023-09-27 18:31:42

我为一个画布有不同的控件模板:

<Application.Resources>
    <ControlTemplate x:Key="Control1" />
    <ControlTemplate x:Key="Control2" />
</Application.Resources>

我想通过我的视图模型属性更改其中一个,如下所示:

private string _template = "Control1";
public string Template
        {
            get
            {
                return _template;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _template = value;
                    OnPropertyChanged("Template");
                }
            }
        }

最后用我的观点:

<UserControl Template="{StaticResource {Binding Template}}" />

但是它不起作用,我该如何解决它?谢谢

如何在视图模型中绑定静态资源键

您可以尝试使用 DataTrigger

<UserControl>
<UserControl.Style>
<Style TargetType="{x:Type UserControl}">
<Setter Property="ControlTemplate" value="{StaticResource Control1}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Template}" Value ="Control1">
<Setter Property="ControlTemplate" value="{StaticResource Control1}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Template}" Value ="Control2">
<Setter Property="ControlTemplate" value="{StaticResource Control2}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Style>
</UserControl>