得到了一些代碼時出現了意外的結果:嵌套類INotifyPropertyChanged的將無法工作
如果我與MYCLASS代替嵌套類,那麼就沒有問題。我錯過了什麼? 如果我將文本(綁定到其他控件)或綁定圖像,則無關緊要。
XAML代碼:
<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>
<DataTemplate x:Key="DataTemplate_Level">
<Image Source="{Binding Path=MyClass.ImageSource}" Width="48" Height="48"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl x:Name="h" ItemTemplate="{DynamicResource DataTemplate_Level}"/>
</Grid>
</Window>
類代碼:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var myClass = new WrappedClass()
{
MyClass = new MyClass()
};
var image = new BitmapImage(new Uri("Tiles.png", UriKind.Relative));
int TileSize = 16;
var cropRectangle = new Int32Rect((int)0, 0, TileSize, TileSize);
var croppedBitmap = new CroppedBitmap(image, cropRectangle);
var observableCollection = new ObservableCollection<WrappedClass>();
observableCollection.Add(myClass);
observableCollection.Add(myClass);
observableCollection.Add(myClass);
h.ItemsSource = observableCollection;
}
public class WrappedClass : INotifyPropertyChanged
{
private MyClass _myClass;
public MyClass MyClass
{
get
{
return _myClass;
}
set
{
_myClass = value;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("MyClass"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MyClass : INotifyPropertyChanged
{
private ImageSource _imageSource;
private string _text = "test";
public MyClass()
{
var image = new BitmapImage(new Uri("Tiles.png", UriKind.Relative));
int TileSize = 16;
var cropRectangle = new Int32Rect((int)0, 0, TileSize, TileSize);
_imageSource = new CroppedBitmap(image, cropRectangle);
}
public string Text
{
get
{
return _text;
}
set
{
_text = value;
PropertyChanged.Invoke(this,new PropertyChangedEventArgs("Text"));
}
}
public ImageSource ImageSource
{
get
{
return _imageSource;
}
set
{
_imageSource = value;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ImageSource"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
}
沒趕上處理器== NULL。在應用程序中(也不是樣本),DynamicResource也有一些奇怪的東西, –