【问题标题】:Binding Style Name and changing the style VIA View Model绑定样式名称并更改样式 VIA View Model
【发布时间】:2013-06-28 09:13:27
【问题描述】:

如何更改元素 VIA 视图模型的样式,就像我想在单击按钮时切换样式一样。

XAML

<Grid x:Name="LayoutRoot"
      DataContext="{Binding Source={StaticResource IndexVMDataSource}}">
  <Button Content="Button"
          HorizontalAlignment="Left"
          Height="42"
          Margin="10,49,0,0"
          VerticalAlignment="Top"
          Width="130"
          Command="{Binding OnCommandName, Mode=OneWay}" />
  <HyperlinkButton Content="HyperlinkButton"
                   HorizontalAlignment="Left"
                   Height="34"
                   Margin="10,10,0,0"
                   VerticalAlignment="Top"
                   Width="216"
                   Style="{Binding QStyle}" />
</Grid>

虚拟机

private string _styleA = "HyperLink-Navi-Container";
private string _styleB = "HyperLink-Navi-Container-2";

private string qStyle;
public string QStyle
{
     get
     {
           return qStyle;
     }
     set
     {
          if (qStyle != value)
          {
               qStyle = value;
               NotifyPropertyChanged(Utility.GetPropertyName(() => QStyle));
          }
     }
}

private ICommand onCommandName = null;
public ICommand OnCommandName
{
     get
     {
         return onCommandName;
     }
     private set
     {
         onCommandName = value;
     }
}

public void Command()
{
     if (QStyle != _styleA)
         QStyle = _styleA;
     else if (QStyle != _styleB)
         QStyle = _styleB;            
}

【问题讨论】:

    标签: silverlight xaml mvvm


    【解决方案1】:

    您的QStyle 属性必须是Style 类型:

    private Style qStyle;
    public Style QStyle
    {
        get { return qStyle; }
        set
        {
            if (qStyle != value)
            {
                 qStyle = value;
                 NotifyPropertyChanged(Utility.GetPropertyName(() => QStyle));
            }
        }
    }
    

    或者您在样式绑定中使用binding converter,它会为给定的字符串(例如样式资源的键)返回适当的Style

    <HyperlinkButton ...
        Style="{Binding QStyle, Converter={StaticResource YourStringToStyleConverter}}" />
    

    由于您没有显示您定义样式的位置,我猜它们在您的用户控件的Resources 中。然后,您可以通过以下方式获取它们:

    Style style = Resources["HyperLink-Navi-Container"] as Style;
    

    如果资源是在 App.xaml 中定义的,您可以编写

    Style style = Application.Current.Resources["HyperLink-Navi-Container"] as Style;
    

    【讨论】:

    • Style style = Resources["HyperLink-Navi-Container"] as Style; 找不到.. 资源在哪里?
    • 我怎么可能知道呢?这是您的应用程序,当您编写private string _styleA = "HyperLink-Navi-Container" 时,我只能猜测它是一个资源键。如果不是,那还有什么?您的样式在哪里定义?请提供更多信息。
    • 而“HyperLink-Navi-Container”是资源键?查看我的编辑。
    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多