【问题标题】:WPF: Bindings not working correctlyWPF:绑定无法正常工作
【发布时间】:2010-10-31 03:03:31
【问题描述】:

假设我有 XAML 之类的

<TabControl Grid.Row="1" Grid.Column="2" ItemsSource="{Binding Tabs}" IsSynchronizedWithCurrentItem="True">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding TabTitle}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <local:UserControl1 Text="{Binding Text}" />
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

我想问TabTitleText 属性是从哪里来的?我认为应该来自Tabs 的每一项,对吗?说 Tabs 是 ObservableCollection&lt;TabViewModel&gt; TabTitleText 应该来自 TabViewModel 属性吧。但这在一定程度上似乎是正确的。 TabTitle 已正确填充,而 Text 未正确填充。

TextUserControl1 中声明为依赖属性,如下所示

public string Text
{
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}

public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new UIPropertyMetadata(""));

当我的标签未绑定到 ObservableCollection&lt;TabViewModel&gt; 时,绑定工作正常

<TabControl Grid.Row="1" Grid.Column="1">
    <TabItem Header="Tab 1">
        <local:UserControl1 Text="Hello" />
    </TabItem>
    <TabItem Header="Tab 2">
        <local:UserControl1 Text="World" />
    </TabItem>
</TabControl>

【问题讨论】:

  • 检查输出窗口是否存在绑定错误
  • 你用一些值初始化 TabViewModel.Text 吗?或者它是空的?另外,您的 TabViewModel 是否实现了 INotifyPropertyChanged 接口?

标签: wpf data-binding xaml dependency-properties


【解决方案1】:

如果您将 UserControl 绑定到代码隐藏文件中的属性,您应该使用

 {Binding RelativeSource={RelativeSource Mode=Self}, Path=Text}

直接绑定只适用于 DataContext

【讨论】:

    【解决方案2】:

    我想我知道问题出在哪里。 UserControl1 中本应由 Text 属性填充的元素不观察该属性的变化。所以有两种方法:

    1) 使用 PropertyChangedCallback:

    public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new UIPropertyMetadata(""),
        new PropertyChangedCallback(OnTextPropertyChanged));
    
    private static void OnTextPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        ((UserControl1)sender).OnTextChanged();
    }
    
    private void OnTextChanged()
    {
        this.myTextBlock.Text = this.Text;
    }
    

    2)棘手的绑定:

    <UserControl x:Class="UserControl1" x:Name="root" ...>
    ...
        <TextBlock Text="{Binding Text, ElementName=root}"/>
    ...
    </UserControl>
    

    【讨论】:

    • 嗯...这仍然不起作用,没有任何错误。我也认为DependencyProperty.Register 的语法是public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new UIPropertyMetadata("", new PropertyChangedCallback(OnTextChanged)));
    • 在 TextChanged 处理程序中放置一个断点并检查属性的值。
    猜你喜欢
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2021-06-25
    • 2021-11-08
    相关资源
    最近更新 更多