我正在尝试通过XAML 绑定图像控件的源属性。 但是我的Image控件中没有显示任何内容。
XAML:
<Window x:Class="ImageSourceBinding.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">
<StackPanel>
<Image Name="MyImage1" Width="32" Height="32" Source="{Binding MyImageSource}"/>
<Image Name="MyImage2" Width="32" Height="32" />
</StackPanel>
</Window>
代码背后:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
ImageSource MyImageSource;
String FilePath = @"C:\Users\UserName\Documents\Map.txt";
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
System.Drawing.Icon ExtractedIcon = System.Drawing.Icon.ExtractAssociatedIcon(FilePath);
MyImageSource = Imaging.CreateBitmapSourceFromHIcon(ExtractedIcon.Handle, new Int32Rect(0, 0, 32, 32), BitmapSizeOptions.FromEmptyOptions());
ExtractedIcon.Dispose();
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("MyImageSource"));
this.Icon = MyImageSource; //This is Working
//MyImage2.Source = MyImageSource; //and this too.
}
}
我可以使用 MyImageSource 来更改Window of Icon。 此外,如果我从Code-Behind设置Source,则图像被正确显示。
答案 0 :(得分:4)
由于您正在使用PropertyChanged并且显然是正确的数据上下文,我假设您的绑定会收到有关MyImageSource
更改的通知,但无法访问它,因为MyImageSource
是私有的而不是属性
尝试使用它来定义MyImageSource
:
public ImageSource MyImageSource { get; private set; }
答案 1 :(得分:1)
您无法绑定到某个字段,只能绑定到某个属性。写一个这样的属性,然后在代码后面分配给属性:
private ImageSource _myImageSource;
public ImageSource MyImageSource {
get { return _myImageSource; }
set {
if (value != _myImageSource)
{
_myImageSource = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyImageSource)));
}
}
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
System.Drawing.Icon ExtractedIcon = System.Drawing.Icon.ExtractAssociatedIcon(FilePath);
MyImageSource = Imaging.CreateBitmapSourceFromHIcon(ExtractedIcon.Handle, new Int32Rect(0, 0, 32, 32), BitmapSizeOptions.FromEmptyOptions());
ExtractedIcon.Dispose();
this.Icon = MyImageSource; //This is Working
}
现在您的绑定应该有效。
建议不要 DataContext = this;
。最好有一个单独的viewmodel类。但它曾经不会杀了你。