我在 ListBox 中有一個 ItemTemplate,其中有 Image(國家標志)和 TextBlock(國家名稱)
串列框:
<ListBox x:Name="countriesList" Background="#a79473" Foreground="#e6d9c4">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="40" Background="#a79473">
<Image Source="{Binding Flag.Source}"/>
<TextBlock Text="{Binding Name}" Foreground="#e6d9c4" FontSize="20"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
國家級:
public class Country
{
public string Name { get; set; }
public Image Flag { get; set; }
public Country()
{
Flag = new Image();
}
}
當 Country 更改 Flag 時,一切正常,但是當 Name 更改時沒有任何反應,
我想當我更改 Name 時,系結仍然系結到舊 Name,但是如何處理呢?
Country country = new Country();
countriesList.Items.Add(country);
country.Name = "test";
country.Flag.Source = flagImage.Source;
PS這是我關于stackoverflow的第一個問題,我希望我在任何地方都沒有出錯:)
uj5u.com熱心網友回復:
每當它被設定為一個新值時,你的Country類應該實作INotifyPropertyChanged并引發該屬性的PropertyChanged事件Name:
public class Country : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; RaisePropertyChanged(); }
}
public Image Flag { get; set; }
public Country()
{
Flag = new Image();
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
設定Source屬性按原樣作業的原因是因為它是一個依賴屬性。附帶說明一下,像這樣的模型Country不應該包含像Image.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/409439.html
標籤:
