Utk*_*tav -1 c# wpf user-interface xaml wpf-controls
我在XAML中设置了两个图像元素的来源.如何使它们指向同一个对象,这样如果其中一个图像的源更改,则第二个图像会自动更改.目前,通过设置XAML图像的源,它们都保持自己的本地副本.例如,我有两个图像元素
<Image x:Name="abc" /> and <Image x:name="def"/>
Run Code Online (Sandbox Code Playgroud)
我设置了abc.Source ="xyz"和def.Source ="xyz".现在两个(abc和def)都有自己的图像副本"xyz".如何让它们指向同一个图像对象.因此没有必要保留2份"xyz".
我不太确定我是否理解正确.我想你可能希望能够一次更改ImageSource并自动更新两个图像,而不是在每次更改时明确设置每张图片的Source.这将是绑定的描述.
这是该案例的实现:
视图模型:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
namespace WpfApplication1
{
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private string _source;
public string Source { get { return _source; } set { _source = value; OnPropertyChanged("Source"); } }
public ICommand ChangeImageCommand { get; private set; }
private List<string> _pics = new List<string>()
{
"/Themes/Evernote.png",
"/Themes/Skype.png",
"/Themes/Twitter.png"
};
private int i = 0;
public MyViewModel()
{
this.Source = _pics[i++];
this.ChangeImageCommand = new ActionCommand(ChangeImage);
}
private void ChangeImage()
{
this.Source = _pics[i++ % _pics.Count];
}
}
public class ActionCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private Action _action;
public ActionCommand(Action action) { _action = action; }
public bool CanExecute(object parameter) { return true; }
public void Execute(object parameter) { if (_action != null) _action(); }
}
}
Run Code Online (Sandbox Code Playgroud)
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="500">
<Window.DataContext>
<local:MyViewModel />
</Window.DataContext>
<StackPanel Background="Maroon">
<Image x:Name="Image1" Source="{Binding Source}" Margin="20" Width="100" />
<Image x:Name="Image2" Source="{Binding Source}" Margin="20" Width="100" />
<Button Command="{Binding ChangeImageCommand}" Content="Change Image" HorizontalAlignment="Center" />
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)