1

如何更改元素 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;            
}
4

1 回答 1

1

您的QStyle财产必须是以下类型Style

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

或者您在 Style 绑定中使用绑定转换器Style,它返回适合给定字符串(例如 Style 资源的键):

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

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

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

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

Style style = Application.Current.Resources["HyperLink-Navi-Container"] as Style;
于 2013-06-28T09:40:12.567 回答