gpt4 book ai didi

c# - 如何将属性绑定(bind)到 WPF 中 Treeview 中的选定节点

转载 作者:太空狗 更新时间:2023-10-30 00:56:00 24 4
gpt4 key购买 nike

如何将自定义属性绑定(bind)到 MVVM 中选定节点的 IsSelected 属性,我已经在运行时将节点加载到 TreeView 中。我正在使用 MVVM

最佳答案

这是一个小例子:

public abstract class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

public class MyViewModel : ViewModel
{
public ObservableCollection<Item> Items
{
get
{
return new ObservableCollection<Item>()
{
new Item() {DisplayValue = "Item1", IsSelected = false, Sample = "Sample: I am Item1"},
new Item() {DisplayValue = "Item2", IsSelected = true, Sample = "Sample: I am Item2"},
new Item() {DisplayValue = "Item3", IsSelected = false, Sample = "Sample: I am Item3"}
};
}
}
}

public class Item : ViewModel
{
public string DisplayValue { get; set; }

private bool _isSelected = false;

public bool IsSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}

private string _sample;

public string Sample
{
get
{
return _sample;
}
set
{
_sample = value;
OnPropertyChanged("Sample");
}
}
}

XAML:

<Window x:Class="WpfApplication93.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication93"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.DataContext>
<local:MyViewModel></local:MyViewModel>
</Grid.DataContext>

<StackPanel>
<TreeView x:Name="myTreeView" ItemsSource="{Binding Items}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TreeViewItem">
<TextBlock Text="{Binding DisplayValue}"></TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>

<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<!-- if you want to customize the appearance of a selected element do it here -->
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>

<Label Content="{Binding ElementName=myTreeView, Path=SelectedItem.Sample}"></Label>
</StackPanel>
</Grid>
</Window>

关于c# - 如何将属性绑定(bind)到 WPF 中 Treeview 中的选定节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8800479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com