WPF两个组合框基于相同的列表

时间:2014-07-20 22:00:24

标签: c# wpf data-binding combobox

我对使用WPF相当新,并且有一个我想要实现的简单场景:

我有两个组合框,cmbSite和cmbLogFiles,我有一个List<LogFileDirectory>,其定义如下:

class LogFileDirectory 
{
    public List<System.IO.FileInfo> Files { get; private set; }
    public string Name { get; private set; }
    public string Path { get; private set; }

    private LogFileDirectory() { }
    public LogFileDirectory(string name, string path)
    {
        this.Name = name;
        this.Path = path;
        this.Files = new List<System.IO.FileInfo>();
        if (System.IO.Directory.Exists(this.Path))
        {
            foreach (string file in System.IO.Directory.GetFiles(this.Path, "*.log", System.IO.SearchOption.TopDirectoryOnly))
                this.Files.Add(new System.IO.FileInfo(file));
        }

    }
}

我的cmbSite绑定到后面代码中List<LogFileDirectory>名称属性,如下所示:

cmbSite.ItemsSource = _logFileInfo.WebServerLogFileDirectories;
cmbSite.SelectedValue = "Path";
cmbSite.DisplayMemberPath = "Name";

我希望cmbLogFiles绑定到当前所选cmbSite的同一List<LogFileDirectory>上的 Files 属性,并过滤到当前选择的cmbSite值的条目LogFileDirectory对象,但我是如果不在cmbSite的ClickEvent处理程序中编写代码(这似乎是基于我的WPF研究的错误方法)并将cmbLogFiles重新绑定到select cmbSite LogFileDirectory,我真的不太确定如何做到这一点。

1 个答案:

答案 0 :(得分:1)

根据@Chris在上述评论中指出的线索,解决方案很简单。

<ComboBox Name="cmbLogFiles" Width="140" ItemsSource="{Binding SelectedItem.Files, ElementName=cmbSite}" />

其中cmbLogFiles的ItemsSource属性指定Binding将是SelectedItem对象(被定义为 LogFileDirectory 的对象)的 Files 属性,并通过元素属性为我的其他组合框(cmbSites)。

我可以通过在窗口上设置DataContext来删除所有代码:

parserView = new Parser();
parserView.DataContext = new LogFileInfo("deathstar");

然后是Parser窗口的后续XAML:

<Window x:Class="Zapora.UI.Parser"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Log File Parser" Height="350" Width="525">
    <StackPanel Orientation="Horizontal" Height="26" VerticalAlignment="Top">
        <Label Content="Web Site:"/>
        <ComboBox  Name="cmbSite" Width="180" ItemsSource="{Binding WebServerLogFileDirectories}" DisplayMemberPath="Name" SelectedValuePath="Path"/>
        <Label Content="Files Available:"/>
        <ComboBox Name="cmbLogFiles" Width="140" ItemsSource="{Binding SelectedItem.Files, ElementName=cmbSite}" />
    </StackPanel>
</Window>