基本的WPF数据绑定问题

时间:2009-12-18 20:01:25

标签: wpf data-binding dependency-properties

我有另一个WPF数据绑定问题...我没有找到任何答案,这让我感到惊讶,因为它似乎非常基本。

基本上,我在代码后面有一个字符串,我希望在GUI中使用文本框建立双向绑定。我认为在后面的代码中创建DependencyProperty然后通过Source绑定将它绑定到TextBox是一件简单的事情。问题是,我不能正确地获得一个或两个部分。

这是我背后的代码中的DependencyProperty定义:

    public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register( "FilePath", typeof(string), typeof(Window1));
    public string FilePath
    {
        get { return (string)GetValue(FilePathProperty); }
        set { SetValue( FilePathProperty, value); }
    }

这是我的XAML:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ReportingInterface Test Application" Height="300" Width="536">

    <Menu DockPanel.Dock="Top">
        <MenuItem Name="menu_plugins" Header="File">
            <MenuItem Header="Open">
                <StackPanel Orientation="Horizontal">
                    <Label>File location:</Label>
                    <TextBox Name="text_filepath" Width="100" Text="{Binding Source=FilePath, Path=FilePath, Mode=TwoWay}"></TextBox>
                    <Button Margin="3" Width="20">...</Button>
                </StackPanel>
            </MenuItem>
        </MenuItem>
    </Menu>

知道的部分显然是错误的是绑定部分......我讨厌浪费人们在这里提出这个问题的时间,但老实说,我对每次搜索都做得不够(但现在至少此请求将填充后续的谷歌搜索)。 :)

谢谢!

2 个答案:

答案 0 :(得分:2)

当您在XAML中定义绑定时,它会绑定到为对象(或它的父对象)设置为DataContext的任何内容。

这通常意味着您将Window的DataContext设置为某个类,然后绑定将起作用:

<TextBox Name="text_filepath" Width="100" Text="{Binding Path=FilePath, Mode=TwoWay}" />

你可以通过在Window的构造函数中添加来解决这个问题:

this.DataContext = this;

这将使绑定对窗口本身起作用。

或者,您可以设置绑定以绑定特定的源对象。在这种情况下,如果您希望能够使用其他东西作为DataContext,但仍希望绑定到Window中定义的依赖项属性,则可以执行以下操作:

<TextBox Name="text_filepath" Width="100" Text="{Binding Path=FilePath, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"></TextBox>

这可以通过告诉绑定找到“Window”类型的第一个祖先,并将其绑定到该对象上的“FilePath”属性。

答案 1 :(得分:1)

对于它的价值,我建议调查MV-VM模式(Model,View,ViewModel) - 实质上,你所做的是让这个类充当你的XAML的DataContext,以及所有有趣的暴露属性/ commands /您作为该类的公共成员(称为ViewModel)公开了什么。

这是一个很好的概述网络广播: MVVM video

这是来自MSDN mag的另一个: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx