WPF如何允许所有树视图项目具有与每个项目关联的相同组合框

时间:2019-03-05 14:41:08

标签: c# wpf mvvm combobox treeview

我在WPF应用程序方面遇到了一个痛点,我理想地希望在这里实现的是带有子项的树形视图,其中每个项旁边都有一个组合框,并且在此组合框中具有3个文本值。如

ParentItem1 下拉包含3个项目的ComboBox     ChildItem1 下拉包含3个项目的ComboBox     ChildItem2 下拉包含3个项目的ComboBox ParentItem2 下拉组合框,其中包含3个项目     ChildItem1 下拉包含3个项目的ComboBox     ChildItem2 下拉包含3个项目的ComboBox     ChildItem3 下拉包含3个项目的ComboBox

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

Xaml代码:

<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,
    }

结果: Result combobox with treeview

直接绑定到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>

结果:

Working CMB

在此先感谢您的帮助:)。如有任何疑问,请通知我。

1 个答案:

答案 0 :(得分:0)

Dropdown控件未获取StateList属性。

您需要命名“窗口”屏幕,然后执行“元素绑定”以获取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">

对于Combox框控件,请使用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>