首页 > 解决方案 > WPF如何允许所有树视图项目具有与每个项目关联的相同组合框

问题描述

关于我的 WPF 应用程序,我遇到了一个痛点,我在这里理想地尝试实现的是一个带有子项的树视图,在每个项旁边都有一个组合框,并且在这个组合框中有 3 个文本值。如

ParentItem1 包含 3 个项目的 下拉 ComboBox ChildItem1包含 3 个项目的下拉 ComboBox ChildItem2包含 3 个项目的下拉 ComboBox ParentItem2包含 3 个项目 的下拉 ComboBox ChildItem1包含 3 个项目的下拉 ComboBox ChildItem2包含 3 个项目的下拉 ComboBox ChildItem3包含 3 个项目的 下拉 ComboBox

幸运的是,我已经为树视图列出了一些虚拟数据并显示了一个组合框,但不幸的是,这 3 个值没有显示。我在这里使用 MVVM 模式,我将数据绑定到视图模型,反之亦然。这是我到目前为止的代码:

Xml代码:

<Grid.Resources>
    <HierarchicalDataTemplate x:Key="servicesKey" DataType="{x:Type src:Service}" ItemsSource="{Binding Path=Children}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" Margin="5,10,0,0" />
            <ComboBox Name="cmbStatusList" 
                      ItemsSource="{Binding StateList}"
                      IsTextSearchEnabled="True"
                      SelectionChanged="cmb_SelectionChanged"
                      DisplayMemberPath="State"
                      IsEditable="True"
                      IsReadOnly="True"
                      SelectedValuePath="StateID"
                      Width="150" 
                      Margin="20,0,0,0">
            <ComboBox.SelectedValue>
                <Binding Path="NewIncident.StateID" Mode="TwoWay" UpdateSourceTrigger="Explicit">
                    <Binding.ValidationRules>
                        <validation:ComboBoxRules />
                    </Binding.ValidationRules>
                </Binding>
            </ComboBox.SelectedValue>
            </ComboBox>
        </StackPanel>
    </HierarchicalDataTemplate>
</Grid.Resources>

<TreeView Name="treeServices"
          ContextMenuOpening="ContextMenu_ContextMenuOpening"
          ItemsSource="{Binding ServiceModel.Services}"
          ItemTemplate="{StaticResource servicesKey}"
          VirtualizingPanel.IsVirtualizing="True"
          Margin="0,0,10,10">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}"  BasedOn="{StaticResource {x:Type TreeViewItem}}"/>
    </TreeView.ItemContainerStyle>
</TreeView>

服务视图模型

public class ServiceViewModel : ViewModelBase
{
    private List<Service> _services;
    public ServiceViewModel()
    {
        _services = new List<Service>();
    }

    public List<Service> Services
    {
        get { return _services; }
        set { _services = value; OnPropertyChanged("Services"); }
    }

    public override void OnChange()
    {
        throw new NotImplementedException();
    }
}
public class Service : INotifyPropertyChanged
{
    public Service(Service parent = null)
    {
        Children = new List<Service>();
    }
    public Guid Guid { get; set; }
    public string Name { get; set; }
    public List<Service> Children { get; set; }
    public string State { get; set; }
    public ServiceState StateID { get; set; }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

模型

    var statesmodel = _oakStatusProvider.GetServiceState()
        .Select(p => new Service()
        {
            StateID = p.StateID,
            State = p.State
        });

        _incidentViewModel.StateList = new List<Service>(statesmodel);
this.DataContext = _incidentViewModel;

获取服务方法

public List<ServiceDTO> GetServiceState()
{
    List<ServiceDTO> servicestatelist = new List<ServiceDTO>
    {
        new ServiceDTO { StateID = ServiceState.Normal, State = "Normal" },
        new ServiceDTO { StateID = ServiceState.Degraded, State = "Degraded" },
        new ServiceDTO { StateID = ServiceState.Critical, State = "Critical" },
    };
    return servicestatelist;
}

CMBbox 中使用的状态

public enum ServiceState
    {
        Normal = 0,
        Degraded = 10,
        Critical = 20,
    }

结果: 带有树视图的结果组合框

直接绑定到 Combobox 工作正常,似乎是 DataTemplete 搞砸了?

                                    <ComboBox Name="cmbSstatusList" 
                                  ItemsSource="{Binding StateList}"
                                  IsTextSearchEnabled="True"
                                  SelectionChanged="cmb_SelectionChanged"
                                  DisplayMemberPath="State"
                                  IsEditable="True"
                                  IsReadOnly="True"
                                  SelectedValuePath="StateID"
                                  materialDesign:HintAssist.Hint="State" 
                                  Style="{StaticResource MaterialDesignFloatingHintComboBox}" 
                                  Width="150" 
                                  Height="45" 
                                  FontSize="15" >
                            <ComboBox.SelectedValue>
                                <Binding Path="NewIncident.StateID" Mode="TwoWay" UpdateSourceTrigger="Explicit">
                                    <Binding.ValidationRules>
                                        <validation:ComboBoxRules />
                                    </Binding.ValidationRules>
                                </Binding>
                            </ComboBox.SelectedValue>
                        </ComboBox>

结果:

工作中巴

提前感谢您的任何帮助和帮助:)。有任何问题请告诉我。

标签: c#wpfmvvmcomboboxtreeview

解决方案


Dropdown 控件未获取 StateList 属性。

您需要为 Window 屏幕命名,然后执行 Element Binding 以获取 Dropdown 控件的 StateList Binding 工作。

<Window x:Class="WpfApp11.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp11"
        mc:Ignorable="d" x:Name="Window1"
        Title="MainWindow" Height="450" Width="800">

对于组合框控件,使用 ElementBinding 来绑定列表。

 <ComboBox Name="cmbStatusList" 
                      ItemsSource="{Binding ElementName=Window1, Path=DataContext.StateList}"
                      IsTextSearchEnabled="True"
                      DisplayMemberPath="State"
                      IsEditable="True"
                      IsReadOnly="True"
                      SelectedValuePath="StateID"
                      Width="150" 
                      Margin="20,0,0,0">
                </ComboBox>

推荐阅读