![](/img/trans.png)
[英]How can I use an IValueConverter to bind to different properties of an object in WPF?
[英]How do I bind the properties of an object to a WPF control?
我有一個Cell類,具有一個名為Color的屬性,並且制作了一個Cell對象列表列表,打算將其用作UniformGrid的綁定源。 統一網格中的單元格應根據對象的Color屬性更改顏色,但是,無論我如何編寫xaml代碼,它都不會改變。 我還嘗試將單元格放置在ObservableCollections中,但是它不起作用,它只是在窗口中顯示為GameOfLife.Cell。
我有這個xaml代碼:
<DataTemplate x:Key="Line">
<ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource CellTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
<DataTemplate x:Key="CellTemplate">
<DataGridCell Content="{Binding}" Background="{Binding Color}"></DataGridCell>
</DataTemplate>
</Window.Resources>
<UniformGrid Background="Red">
<ItemsControl x:Name="Cells" ItemTemplate="{DynamicResource Line}"/>
</UniformGrid>
這就是我嘗試綁定單元格對象的方式:
public MainWindow()
{
InitializeComponent();
ObservableCollection<ObservableCollection<Cell>> cells = new ObservableCollection<ObservableCollection<Cell>>();
cells.Add(new ObservableCollection<Cell> { new Cell(State.Alive), new Cell(), new Cell(State.Alive) });
cells.Add(new ObservableCollection<Cell> { new Cell(State.Alive), new Cell(), new Cell() });
cells.Add(new ObservableCollection<Cell> { new Cell(), new Cell(State.Alive), new Cell() });
Cells.ItemsSource = cells;
}
單元格的隱式狀態為State.Dead。
我想知道的是為什么它不起作用以及如何使其起作用。
代替嵌套的ItemsControl,將具有UniformGrid作為其ItemsPanel的單個ItemsControl(例如,使用Border或Grid可視化單元格)會更簡單:
<ItemsControl ItemsSource="{Binding Cells}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="10"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border>
<Border.Background>
<SolidColorBrush Color="{Binding Color}"/>
</Border.Background>
<!-- optional child element here -->
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
視圖模型如下所示。 請注意,Cell類實現INotifyPropertyChanged
接口以通知其屬性更改。 除非要動態更改網格大小,否則不需要使用Cell對象的ObservableCollection。 一個簡單的列表就足夠了。
public enum CellState
{
Dead, Active
}
public class Cell : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private CellState state;
public CellState State
{
get { return state; }
set
{
state = value;
NotifyPropertyChanged("State");
NotifyPropertyChanged("Color");
}
}
public Color Color
{
get { return state == CellState.Dead ? Colors.Red : Colors.Green; }
}
}
public class ViewModel
{
public List<Cell> Cells { get; } = new List<Cell>();
}
並像這樣初始化:
public MainWindow()
{
InitializeComponent();
var vm = new ViewModel();
for (int i = 0; i < 100; i++)
{
vm.Cells.Add(new Cell { State = i % 3 == 0 ? CellState.Dead : CellState.Active });
}
DataContext = vm;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.