使用ObjectDataProvider实例化对象

时间:2012-01-26 18:42:00

标签: wpf

我是WPF的新手,我正在尝试使用ObjectDataProvider创建一个对象,然后在后面的代码中使用它。更具体地说,我希望在将文本输入文本框时更新对象。这是xaml:

<Window x:Class="bindings.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local ="clr-namespace:bindings"

    Title="Bindings" Height="410" Width="1044">
<Window.Resources>
    <ObjectDataProvider x:Key ="MyStringData" ObjectType="{x:Type local:MyStrings}" />
</Window.Resources>

<StackPanel>
    <TextBox Height="23" Name="textBox1" Width="120" KeyDown="textBox1_KeyDown" />
    <ListBox Name="theListBox" Width="200" Height="79" 
  ItemsSource ="{Binding Source={StaticResource MyStringData}}"/>
</StackPanel>

这是背后的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {

        }

    }
}
public class MyStrings : List<String>
{
    public MyStrings()
    {
        this.Add("Test1");
        this.Add("Test2");
        this.Add("Test3");
        this.Add("Test4");
    }
}

我的问题是我用什么来引用ObjectDataProvider创建的对象,这样我就可以操作它创建的MyStrings实例。感谢。

新xaml:

<Window x:Class="bindings.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local ="clr-namespace:bindings"
    Title="Bindings" Height="410" Width="1044">
<Window.Resources>
    <ObjectDataProvider x:Key ="MyStringData" ObjectType="{x:Type local:MyStrings}" x:Name="myProvider" />
</Window.Resources>
<StackPanel>
    <TextBox Height="23" Name="textBox1" Width="120" KeyDown="textBox1_KeyDown" />
    <ListBox Name="theListBox" Width="200" Height="79" 
  ItemsSource ="{Binding Source={StaticResource MyStringData}}"/>
</StackPanel>

新守则背后:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            MyStrings temp = myProvider.ObjectInstance; 
        }

    }
}
public class MyStrings : List<String>
{
    public MyStrings()
    {
        this.Add("Test1");
        this.Add("Test2");
        this.Add("Test3");
        this.Add("Test4");
    }
}

1 个答案:

答案 0 :(得分:3)

你看过ObjectInstance财产吗?

http://msdn.microsoft.com/en-us/library/system.windows.data.objectdataprovider.objectinstance.aspx

如果您给ObjectDataProvider一个名字,例如:

<ObjectDataProvider x:Key ="MyStringData" ObjectType="{x:Type local:MyStrings}" x:Name="myProvider" />

然后在你的代码中你可以做到:

myProvider.ObjectInstance

不要忘记检查NULL以确保它确实已创建。