【问题标题】:Binding to runtime object instance绑定到运行时对象实例
【发布时间】:2011-11-20 01:14:27
【问题描述】:

我在这里转圈。我已经掌握了 XmlDataProvider 绑定的窍门,但我使用的文件似乎太大而无法动态绑定(50Mb 不起作用;2Mb 有效)。因此,我使用从 XSD 生成的代码将数据加载到类中。

但是,由于缺乏知识,我无法绑定到 CLR 对象。我正在使用 Visual Studio 2008 Pro、C# 和 .Net 3.5。

这是 XAML 文件:

<Window x:Class="WpfObjectText.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfObjectText"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.Resources>
            <ObjectDataProvider x:Key="simpleBinding" ObjectType="{x:Type local:ExampleClass}"/>
        </Grid.Resources>
        <StackPanel>
            <TextBox Name="textBox1" Text="{Binding Path=simpleBinding}" />
        </StackPanel>
    </Grid>
</Window>

以及背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfObjectText
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public ExampleClass TestInstance = new ExampleClass("Hello, world!");

        public Window1()
        {
            InitializeComponent();
        }
    }

    public class ExampleClass
    {
        public string TestString { get; set; }

        public ExampleClass(string initialText)
        {
            TestString = initialText;
        }
    }

}

我刻意保持简单,这样我就可以迈出小步。我在这里要做的就是从ExampleClass 的实例填充文本框,并在文本框更改(即双向)时更新TestString 字段。我知道我可以在绑定中设置 MethodName,该绑定在 ListBoxes 中可以在一定程度上起作用,但这对我来说似乎并不意味着双向。来自 Delphi7 Win32 程序员,这对我来说是陌生的领域!

感谢您的帮助。

【问题讨论】:

    标签: c# wpf binding .net-3.5


    【解决方案1】:

    这些是必要的更改:

    <TextBox Name="textBox1" Text="{Binding Path=TestString}" />
    

    然后在构造函数中:

    DataContext = TestInstance;
    

    如果我对问题的理解是正确的,那么您根本不需要 Grid.Resources 部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2013-12-30
      • 2013-05-27
      相关资源
      最近更新 更多