我有一个带有XAML的UserControl:
<StackPanel>
<Label HorizontalContentAlignment="Center">
<Rectangle Name="iconContainer" Height="120" Width="120" Fill="#FF045189">
<Rectangle.OpacityMask>
<VisualBrush Visual="{DynamicResource appbar_disconnect}"/>
</Rectangle.OpacityMask>
</Rectangle>
</Label>
<TextBlock Name="tBlockPortStatus" Foreground="#FF7C7676" FontWeight="Bold" FontSize="15" Margin="3" TextAlignment="Center" HorizontalAlignment="Center" TextWrapping="Wrap">PORT STATUS (Testing wrapping text abilities for this control)</TextBlock>
</StackPanel>
我需要更改图标(名为 appbar_disconnect )并使用Code Behind或MVVM使用另一个DynamicResource
(例如 appbar_connect )。
我怎样才能做到这一点?
此致
答案 0 :(得分:0)
您的案例似乎使用Trigger
而不是DynamicResource
处理得更好,但如果您坚持使用DynamicResource
,则基本上需要定义您的状态&#39;图标/图像作为App.xaml文件中的资源:
<Application.Resources>
<Image Source="Icons/disconnect.png" x:Key="AppbarDisconnect"/>
<Image Source="Icons/connect.png" x:Key="AppbarConnect"/>
<Image Source="Icons/undefined.png" x:Key="AppbarStatus"/>
</Application.Resources>
假设您的UserControl
看起来像这样:
<StackPanel>
<Label HorizontalContentAlignment="Center">
<Rectangle Name="IconContainer" Height="120" Width="120" Fill="#FF045189">
<Rectangle.OpacityMask>
<VisualBrush Visual="{DynamicResource AppbarStatus}"/>
</Rectangle.OpacityMask>
</Rectangle>
</Label>
<TextBlock Name="TBlockPortStatus" Foreground="#FF7C7676" FontWeight="Bold" FontSize="15" Margin="3" TextAlignment="Center" HorizontalAlignment="Center" TextWrapping="Wrap">PORT STATUS (Testing wrapping text abilities for this control)</TextBlock>
</StackPanel>
您可以更新特定事件的AppbarStatus
资源(来自后面的代码或来自viewmodel),如下所示:
Application.Current.Resources["AppbarStatus"] = Application.Current.Resources["AppbarDisconnect"];
<强>更新强>
如果您想使用DataTrigger
,只需添加一个属性即可将连接状态保存到您的用户控件:
private bool _connetionStatus;
public bool ConnectionStatus
{
get { return _connetionStatus; }
set
{
if (value == _connetionStatus) return;
_connetionStatus = value;
OnPropertyChanged();
}
}
DataTrigger
应该是自我解释的:
<StackPanel>
<Label HorizontalContentAlignment="Center">
<Rectangle Name="IconContainer" Height="120" Width="120" Fill="#FF045189">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="OpacityMask">
<Setter.Value>
<VisualBrush Visual="{DynamicResource AppbarDisconnect}"/>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding ConnectionStatus}" Value="true">
<Setter Property="OpacityMask">
<Setter.Value>
<VisualBrush Visual="{DynamicResource AppbarConnect}"/>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
</Label>
<TextBlock Name="TBlockPortStatus" Foreground="#FF7C7676" FontWeight="Bold" FontSize="15" Margin="3" TextAlignment="Center" HorizontalAlignment="Center" TextWrapping="Wrap">PORT STATUS (Testing wrapping text abilities for this control)</TextBlock>
</StackPanel>