c# - ComboBox 绑定(bind)到自定义 ViewModel

标签 c# wpf xaml data-binding mvvm

我正在开发一个 WPF 项目。这是我的 XAML 代码:

<Window x:Class="MyNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:l="clr-namespace:MyNamespace" 
        xmlns:p="clr-namespace:MyNamespace.Properties"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
        Height="500" Title="{x:Static p:Resources.Title}" Width="500"
        WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <l:BrowsersViewModel x:Key="BrowsersViewModel"/>
    </Window.Resources>
    <Canvas Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"
            DataContext="{StaticResource BrowsersViewModel}">
        <ComboBox Canvas.Left="10" Canvas.Top="10" DisplayMemberPath="Name"
                  ItemsSource="{Binding Path=Items}" 
                  SelectedItem="{Binding Mode=TwoWay, Path=SelectedItem}"
                  SelectedValuePath="Process" Width="379"/>
        <Button Content="Repopulate" Canvas.Right="10" 
                Canvas.Top="10" Width="75"/>
    </Canvas>
</Window>

这是我的 ViewModel 代码:
// BrowserInstance is a simple struct with two public fields:
// 1) System.Diagnostics.Process Process
// 2) System.String Name
public sealed class BrowsersViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private BrowserInstance m_SelectedItem;
    public BrowserInstance SelectedItem
    {
        get { return m_SelectedItem; }
        set
        {
            if (m_SelectedItem != value)
            {
                m_SelectedItem = value;
                NotifyPropertyChanged("SelectedItem");
            }
        }
    }

    private ObservableCollection<BrowserInstance> m_Items;
    public ObservableCollection<BrowserInstance> Items
    { 
        get { return m_Items; }
        set
        {
            if (m_Items != value)
            {
                m_Items = value;
                NotifyPropertyChanged("Items");
            }
        }
    }

    public BrowsersViewModel()
    {
        m_Items = new ObservableCollection<BrowserInstance>();
        Populate();
    }

    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, (new PropertyChangedEventArgs(propertyName)));
    }

    public void Populate()
    {
        foreach (Process process in Process.GetProcessesByName("chrome"))
        {
            BrowserInstance instance = new BrowserInstance();
            instance.Process = process;
            instance.Name = "[Chrome] " 
                         + process.Handle.ToString() 
                         + " " + ((process.MainWindowTitle.Length > 0) ? 
                                        process.MainWindowTitle : "NULL");

            m_Items.Add(instance);
        }

        NotifyPropertyChanged("Items");
    }
}

我真的很难让这个工作。我到处查看了大量示例,但仍然找不到使一切按预期工作的解决方案。

1) 我在 ComboBox 下拉列表中看到很多值,但它们都是空的。我想显示 BrowserInstance.Name组合框内的属性并检索 BrowserInstance.Process选择项目时的值。

2) 当应用程序启动时,会检查当前正在运行的浏览器进程以填充 ComboBox。如果没有找到正在运行的实例,我怎么能在我的 ComboBox 中显示一条消息,例如“没有找到实例!”?

3) 如果在应用统计时发现一个或多个浏览器实例,如何默认选择第一个?

4) Repopulate 按钮将用于重新检查用户正在运行的浏览器实例。假设之前选择的实例仍在运行……我怎样才能让那个实例保持选中状态?如果之前选择的实例不再运行,我如何再次默认选择第一个?

非常感谢!

编辑:这是我当前的代码

主窗口:
public MainWindow()
{
    InitializeComponent();
    DataContext = m_BrowserInstances = new BrowserInstancesViewModel();
}

private void OnClickButtonRefresh(Object sender, RoutedEventArgs e)
{
    m_BrowserInstances.Populate();
}

BrowserInstancesViewModel:
public void Populate()
{
    BrowserInstance selectedItem = m_SelectedItem;
    List<BrowserInstance> items = new List<BrowserInstance>();

    foreach (Process process in Process.GetProcessesByName("chrome"))
        items.Add(new BrowserInstance(process));

    if (items.Count > 0)
    {
        m_Items = new ObservableCollection<BrowserInstance>(items.OrderBy(x => x.Process.Id));

        if ((selectedItem != null) && (m_Items.SingleOrDefault(NewMethod(selectedItem)) != null))
            m_SelectedItem = selectedItem;
        else
            m_SelectedItem = m_Items[0];

        m_Enabled = true;
    }
    else
    {
        m_Items = new ObservableCollection<BrowserInstance>() { (new BrowserInstance()) };
        m_SelectedItem = m_Items[0];

        m_Enabled = false;
    }

    NotifyPropertyChanged("Enabled");
    NotifyPropertyChanged("Items");
    NotifyPropertyChanged("SelectedItem");
}

最佳答案

BrowserInstance is a simple struct with two public fields:



WPF 不支持对字段进行数据绑定(bind)。只有属性。

这应该有效:
public class BrowserInstance
{
    public string Name { get; set; }

    public Process Process { get; set; }
}

关于c# - ComboBox 绑定(bind)到自定义 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16159681/

相关文章:

c# - 为什么要使用强命名程序集?

c# - 根据格式验证字符串

wpf - 子菜单项命令 MVVM

c# - 如何在 WPF 中使用关闭按钮关闭选项卡?

c# - 类型 'Style' 的值不能添加到类型 'UIElementCollection' 的集合或字典中

c# - 从另一个表单更新文本框。 C#

c# - 如何为更新和保存配置 NHIbernate 事件监听器?

c# - 通知图标附近出现小气球/框

c# - 在 C# 中更改网格的 Canvas.ZIndex

c# - UWP 阻止 AutosuggestBox 自动聚焦