【问题标题】:WP8.1/WinRT User Control Binding from Bound Dependency Property来自绑定依赖属性的 WP8.1/WinRT 用户控件绑定
【发布时间】:2014-10-21 17:08:06
【问题描述】:

我有一个将多个属性传递给内部文本块的用户控件,如下所示:

<UserControl x:Name="Root">

     <Grid>
         <TextBlock x:Name="ContentBlock" 
                    TextWrapping="WrapWholeWords"
                    FontFamily="{Binding FontFamily}"
                    FontWeight="{Binding FontWeight}"
                    Text="{Binding Text}"
                    LineHeight="{Binding LineHeight}"
                    Foreground="{Binding Foreground}"
                    />
     </Grid>
 </UserControl>

在用户控件中我有以下内容:

public CustomTextBlock()            
{
    this.InitializeComponent();
    (this.Content as FrameworkElement).DataContext = this;
}

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text",
        typeof(string), typeof(CustomTextBlock), null);
public string Text
{
    get { return (string)GetValue(TextProperty); }
    set { SetValueDp(TextProperty, value); }
}

public event PropertyChangedEventHandler PropertyChanged;

public void SetValueDp(DependencyProperty property, object value, [CallerMemberName]string propertyName = null)
{
    SetValue(property, value);
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

我在使用这个控件的地方绑定了一些属性,如下所示:

<controls:CustomTextBlock Text="{Binding Question.Text}"
                            FontSize="30"
                            MaxHeight="130"
                            Margin="0, 0, 10, 0"/>

但是,文本没有正确地通过绑定传递到控件中。我所看到的一切都说这应该有效,但事实并非如此。任何想法是什么导致我的文本没有传递到依赖属性?

【问题讨论】:

  • 在我看来是正确的...您在“输出”窗口中看到任何绑定错误吗?
  • 没有我可以看到的绑定错误,没有。

标签: c# xaml windows-runtime windows-phone-8.1


【解决方案1】:

您的控件属于CustomTextBlock 类型,但该属性定义为typeof(ShrinkingTextBlock) 拥有。这些需要匹配才能使绑定起作用。

【讨论】:

  • 抱歉,匿名化代码时遗漏了。它们在实际代码中确实匹配(已编辑修复)
  • 在控件尚未加载但已创建控件时更改 DataContext 可能不会引发对绑定的更新。
  • 如果您只用SetValue 替换SetValueDp 并删除INotifyPropertyChanged 实现,它是否有效?控件不应该真正实现它。
  • 没有。当直接 SetValue 不起作用时,我添加了 SetValueDp。
  • 我只需将更改处理程序添加到Text 属性并手动更新TextBlockText。它实际上会为您节省一些周期。
猜你喜欢
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 2012-08-29
  • 1970-01-01
  • 2023-03-11
  • 2019-05-26
相关资源
最近更新 更多