Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在编译时将ListBox ItemsSource绑定到方法调用结果?_C#_Wpf_Binding - Fatal编程技术网

C# 在编译时将ListBox ItemsSource绑定到方法调用结果?

C# 在编译时将ListBox ItemsSource绑定到方法调用结果?,c#,wpf,binding,C#,Wpf,Binding,我不熟悉WPF数据绑定 我希望将表单上的列表框绑定到以下方法调用的结果: RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32) .OpenSubKey(@"SOFTWARE\Vendor\Product\Systems").GetSubKeyNames(); 目前,我正在运行时分配ListBox.ItemsSource=(方法)加载()事件处理程序。但这意味着在表单编辑器中查看控件配置时,

我不熟悉WPF数据绑定

我希望将表单上的列表框绑定到以下方法调用的结果:

RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)
    .OpenSubKey(@"SOFTWARE\Vendor\Product\Systems").GetSubKeyNames();
目前,我正在运行时分配
ListBox.ItemsSource=(方法)加载()事件处理程序。但这意味着在表单编辑器中查看控件配置时,控件的源数据不明显

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


MSDN文档中的大多数示例都将控件绑定到静态资源,如内嵌XAML资源。我注意到有一个类提供了“[…]绑定到方法结果的能力。”但是我发现ObjectDataProvider文档中的示例非常混乱。我希望您能提供一些建议,说明这是否是进行绑定的正确方法,如果是,在声明ObjectDataProvider时使用什么语法。

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

相反,您应该考虑实现一个分离的表示模式,例如通过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();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Windows;
使用Microsoft.Win32;
命名空间WpfApplication10{
公共类视图模型{
公共数字项目{
获取{return RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,RegistryView.Registry32).OpenSubKey(@“SOFTWARE\Vendor\Product\Systems”).GetSubKeyNames();}
}
}
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口{
公共主窗口(){
初始化组件();
DataContext=新的ViewModel();
}
}
}

谢谢,韦恩,我会调查的。