【问题标题】:Binding ListBox ItemsSource to method call results at compile time?在编译时将 ListBox ItemsSource 绑定到方法调用结果?
【发布时间】:2010-12-10 02:33:00
【问题描述】:

我是 WPF 数据绑定的新手。

我想绑定到以下方法调用的结果的表单上有一个 ListBox:

RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)
    .OpenSubKey(@"SOFTWARE\Vendor\Product\Systems").GetSubKeyNames();

目前我正在运行时通过在 Window_Loaded() 事件处理程序中分配 ListBox.ItemsSource = (method); 来执行此操作。但这意味着在表单编辑器中查看控件配置时,控件的源数据并不明显。

有没有办法在 XAML 中配置此绑定,使其在表单编辑器中可见,从而使代码的行为更易于理解?

MSDN 文档中的大多数示例将控件绑定到静态资源,例如内联 XAML 资源。我注意到有一个ObjectDataProvider 类提供“[...] 绑定到方法结果的能力”。但是,我发现 ObjectDataProvider 文档中的示例非常令人困惑。对于这是否是执行此绑定的正确方法,如果是,在声明 ObjectDataProvider 时使用什么语法,我将不胜感激。

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    简而言之,我认为您不能直接在 XAML 中使用如此复杂的语句。正如您所发现的,可以绑定到通过 ObjectDataProvider 调用对象方法的结果,但您的表达式是一个方法调用链,我认为不能直接在 XAML 中使用它来获取 ObjectDataProvider。

    您应该考虑实现一个分离的表示模式,例如Model-View-ViewModel,以通过 ViewModel 上的集合属性公开表达式的结果,然后将其绑定为视图(窗口)的 DataContext。

    类似:

    MainWindow.xaml

    <Window x:Class="WpfApplication10.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <ItemsControl ItemsSource="{Binding Items}"/>
        </Grid>
    </Window>
    

    MainWindow.cs

    using System;
    using System.Collections.Generic;
    using System.Windows;
    using Microsoft.Win32;
    
    namespace WpfApplication10 {
        public class ViewModel {
            public IEnumerable<String> Items {
                get { return RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Vendor\Product\Systems").GetSubKeyNames(); }
            }
        }
    
        /// <summary>
        ///   Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window {
            public MainWindow() {
                InitializeComponent();
                DataContext = new ViewModel();
            }
        }
    }
    

    【讨论】:

    • 谢谢韦恩,我会调查的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多