【问题标题】:Dependency propery Binding Problem依赖属性绑定问题
【发布时间】:2010-03-16 17:36:32
【问题描述】:

主窗口

<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;


    } 
} 

我在用户控件依赖属性中获取我的值,但我无法将我的值绑定到文本框。我使用这样来绑定 Text="{Binding Text}" 是否正确,或者如何绑定我的值在用户控制中

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

谁能看看有什么问题,

一切正常,但我无法绑定文本框中的值,

当您单击按钮时,您可以在消息框中看到传递给用户控件的值,但我无法在文本框中绑定该值。

为什么????

【问题讨论】:

  • 最好在您的问题中包含相关代码。 (几乎)没有人会下载您的整个项目,查找相关部分,然后尝试查找问题。保留链接,但另外提供相关代码部分!
  • @gehho,我完全同意你的看法。我决定试一试,最多 30 秒。
  • @deepak,我这样做只是因为你是新人。以后请遵照gehho的建议。

标签: wpf user-controls dependencies


【解决方案1】:

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

通过设置 Text 属性,您失去了绑定。本地属性设置比绑定具有更高的优先级。见this blog

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2010-10-09
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多