我目前正在研究 WPF 应用程序 MVVM 模式,我必须在树视图和网格之间创建某种关系。关系基于 ID。这个想法是突出显示 id 等于树节点 id 的行。
显示颜色属性
public Brush DisplayColor
{
set
{
_displayColor = value;
NotifyPropertyChanged("DisplayColor");
}
get { return _displayColor; }
}
选择 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;
}
}
// 在网格中搜索匹配的Id
public void SearchGrid(int id, ObservableCollection<MessageFieldViewModel> msgField)
{
if (msgField.Any())
DisplayColor = msgField.Last().Id == id ? Brushes.CadetBlue : Brushes.Black;
}
XAML:调用显示颜色属性以突出显示匹配的 id。数据网格
树视图:
<TreeView Margin="644,137,6,6" Grid.RowSpan="2" ItemsSource="{Binding MessageElements[0].Children, Mode=TwoWay}"
SelectedItemChanged="TreeView_OnSelectedItemChanged">
树视图选择项的代码隐藏;
readonly MainWindowModel _mainWindowModel = new MainWindowModel();
private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (_mainWindowModel != null)
_mainWindowModel.SelectedMessageElement = (MessageElementViewModel)e.NewValue;
}
编辑:
<DataGrid ItemsSource="{Binding MessageFields}" Margin="4,0,380,6" Grid.Row="2" AutoGenerateColumns="False" IsReadOnly="True" SelectedValue="{Binding SelectedMessageField}"
RowBackground="{Binding Path=DisplayColor}">
<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>
为什么我的显示颜色属性不适用于匹配的 ID?
谢谢你们。