如何更改元素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>
VM
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;
}
答案 0 :(得分: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
(例如,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;