依赖属性绑定问题

时间:2010-03-16 07:13:31

标签: wpf user-controls dependencies

主窗口

<Window x:Class="dep2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:dep2"
    Title="Window1" Height="300" Width="381">
    <Grid>
        <local:UserControl1></local:UserControl1>
        <Button Height="23" HorizontalAlignment="Right" Margin="0,0,77,36" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Button</Button>
    </Grid>
</Window>

public partial class Window1 : Window
{
    UserControl1 uc = new UserControl1();
    public Window1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        uc.InfoText = "SAMPLE";
    }
}

我的用户控制

<UserControl x:Class="dep2.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="32" Width="300">
    <Grid Height="30">
        <StackPanel Background="LightCyan">
            <TextBox Height="21" Name="textBlock1" Width="120"  Text="{Binding Text}" />
        </StackPanel>


    </Grid>
</UserControl>



public partial class UserControl1 : UserControl
{
    public string InfoText
    {
        get
        {
            return (string)GetValue(InfoTextProperty);
        }
        set
        {
            SetValue(InfoTextProperty, value);
        }
    }

    public static readonly DependencyProperty InfoTextProperty =
       DependencyProperty.Register(
          "InfoText",
          typeof(string),
          typeof(UserControl1),
          new FrameworkPropertyMetadata(
             new PropertyChangedCallback(ChangeText)));

    private static void ChangeText(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        (source as UserControl1).UpdateText(e.NewValue.ToString());
    }

    private void UpdateText(string NewText)
    {

        textBox1.Text = NewText;

    } 


    public UserControl1()
    { 
        InitializeComponent();
        DataContext = this;


    } 
} 

我在用户控件依赖属性中得到了我的价值,但我无法将我的值绑定到文本box.am使用这样绑定Text =“{Binding Text}”是对的,或者如何绑定我的值在用户控制

我在这里附上了我的示例项目, http://cid-08ec3041618e8ee4.skydrive.live.com/self.aspx/.SharedFavorites/dep2.rar

任何人都可以看,并告诉他们错误,

everythng运作良好,但我不能将值绑定在文本框中,

当你点击按钮时,你可以在消息框中看到传递给usercontrol的值,但我不能在文本框中绑定该值。

为什么????

1 个答案:

答案 0 :(得分:2)

您的代码处理依赖项属性的回调并直接设置文本框值。这不是此回调的作用。

通过设置Text属性,您已经失去了绑定。本地属性设置的优先级高于绑定。见this blog

相关问题