我正在研究 WPF 应用程序 MVVM 模式,我必须在其中创建 aTreeView
和 a之间的某种关系Grid
。这个想法是突出显示 id 等于树节点 id 的行。
显示颜色属性
public Brush DisplayColor
{
set
{
_displayColor = value;
NotifyPropertyChanged("DisplayColor");
}
get { return _displayColor; }
}
**Select TreeNode value.id**
private MessageElementViewModel _selectedMessageElement;
public MessageElementViewModel SelectedMessageElement
{
set
{
if (_selectedMessageElement == value) return;
this._selectedMessageElement = value;
SearchGrid(value.Id, messageFields);
}
get
{
return this._selectedMessageElement;
}
}
// search matching Id in the grid
public void SearchGrid(int id, ObservableCollection<MessageFieldViewModel> msgField)
{
if (msgField.Any())
DisplayColor = msgField.Last().Id == id ? Brushes.CadetBlue : Brushes.Black;
}
XAML: Call the display color property to highlight a matching id.
DataGrid
<DataGrid ItemsSource="{Binding MessageFields}" Margin="4,0,380,6" Grid.Row="2" AutoGenerateColumns="False" IsReadOnly="True" SelectedValue="{Binding SelectedMessageField, Mode=TwoWay}"
RowBackground="{Binding Path=DisplayColor}">
TreeView:
<TreeView Margin="644,137,6,6" Grid.RowSpan="2" ItemsSource="{Binding MessageElements[0].Children[0].Children, Mode=TwoWay}"
SelectedItemChanged="TreeView_OnSelectedItemChanged"
SelectedValuePath="Id">
Code Behind for treeview select item;
readonly MainWindowModel _mainWindowModel = new MainWindowModel();
private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (_mainWindowModel != null)
_mainWindowModel.SelectedMessageElement = (MessageElementViewModel)e.NewValue;
}
编辑:
<DataGrid Name="Datagrid" ItemsSource="{Binding MessageFields}" Margin="4,0,380,6" Grid.Row="2" AutoGenerateColumns="False" IsReadOnly="True" SelectedValue="{Binding SelectedMessageField}"
AlternatingRowBackground ="{Binding Path=DisplayColor}" RowBackground="{Binding Path=DisplayColor}" Background="CadetBlue">
<DataGrid.Columns >
<DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="*" /> <!--Foreground="{Binding Path=DisplayColor}-->
<DataGridTextColumn Header="Code" Binding="{Binding Code}" Width="*" />
<DataGridTextColumn Header="Field Name" Binding="{Binding Name}" Width="*" />
<DataGridTextColumn Header="Position" Binding="{Binding Position}" Width="*" />
<DataGridTextColumn Header="Length" Binding="{Binding Length}" Width="*" />
</DataGrid.Columns>
</DataGrid>
为什么我的显示颜色属性不适用于匹配的 ID?