BSc*_*ker 16 c# wpf icons button
我目前有一个按钮,上面有一个图标/图像.我在XAML中配置了按钮和图像:
<Button Height="69" HorizontalAlignment="Left" Margin="-2,0,0,0" Name="toggleBroadcast" VerticalAlignment="Top" Width="64" Grid.Row="1" Opacity="0.5" Click="changeBroadcastState_Click">
<Image Source="Images\playIcon.png" />
</Button>
Run Code Online (Sandbox Code Playgroud)
我需要能够以编程方式将此按钮的图像从playIcon更改为stopIcon.我怎样才能做到这一点?
d.m*_*ada 32
您可以通过事件处理程序更改按钮的内容来实现此目的.
您可以将"播放"图标和"停止"图标都设置为资源,Window.Resources
如下所示:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Image x:Key="Play" Source="/WpfApplication1;component/Play_Icon.png" Height="50" Width="50" />
<Image x:Key="Stop" Source="/WpfApplication1;component/Stop_Icon.png" Height="50" Width="50"/>
</Window.Resources>
<Grid>
<Button Click="Button_Click" Name="MediaButton">
<DynamicResource ResourceKey="Play"/>
</Button>
</Grid>
Run Code Online (Sandbox Code Playgroud)
现在,当单击按钮时,您只需将按钮的内容更改为其他资源(停止图标).在按钮的事件处理程序中,您可以执行以下操作:
C#
private void Button_Click(object sender, RoutedEventArgs e)
{
if (MediaButton.Content == FindResource("Play"))
{
MediaButton.Content = FindResource("Stop");
}
else
{
MediaButton.Content = FindResource("Play");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:更短的表示法
MediaButton.Content = FindResource(MediaButton.Content == FindResource("Play") ? "Stop" : "Play");
Run Code Online (Sandbox Code Playgroud)
希望这有帮助,如果您有任何疑问,请告诉我.
如果您有图像定义,则如下所示:
<Image Source="{Binding ImageSource}" Stretch="Fill"/>
Run Code Online (Sandbox Code Playgroud)
然后,在您要执行切换的代码中,只需执行以下操作:
ImageSource = image;
Run Code Online (Sandbox Code Playgroud)
其中image
定义为:
image = new BitmapImage(new Uri("/Application;component/Resources/pause.png", UriKind.Relative));
Run Code Online (Sandbox Code Playgroud)
当然,它确实依赖于您使用MVVM模式并INotifyPropertyChanged
在代码中实现接口。
在更改条件的图像样式(/edit) 中使用 DataTrigger (edit):
<Button Height="69" HorizontalAlignment="Left" Margin="-2,0,0,0" Name="toggleBroadcast" VerticalAlignment="Top" Width="64" Grid.Row="1" Opacity="0.5" Click="changeBroadcastState_Click">
<Image>
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="Images\playIcon.png" />
<Style.Triggers>
<DataTrigger Binding="{Binding myCondition}" Value="True">
<Setter Property="Source" Value="Images\stopIcon.png" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Button>
Run Code Online (Sandbox Code Playgroud)
myCondition
然后该变量将是您的 ViewModel(或更一般地说,Control 的 DataContext)中的一个布尔属性,类似于
public bool myCondition { get { return ([whatever that condition might be]); } }
Run Code Online (Sandbox Code Playgroud)
这也可能包括一个 setter,也可能是一个简单的 auto 属性。与其他 MVVM 答案一样,它将依赖 ViewModel 来实现INotifyPropertyChanged
.
好消息是,一旦条件不再满足,DataTrigger 会自动将 Source 属性设置回其原始值。
免责声明:我现在没有办法测试它,所以用一粒盐和可能的一些调试工作来对待它......