自定义用户控件文本块.文本绑定



我有一个自定义用户控件,它有一个文本块,其文本有时会更改。文本块代码是

XAML:

<TextBlock Text="{Binding ElementName=dashboardcounter, Path=Counter}" FontFamily="{Binding ElementName=dashboardcounter, Path=FontFamily}"   HorizontalAlignment="Left" Margin="17,5,0,0" VerticalAlignment="Top" FontSize="32" Foreground="#FF5C636C"/>

。.cs:

private static readonly DependencyProperty CounterProperty = DependencyProperty.Register("Counter", typeof(string), typeof(DashboardCounter));
public string Counter
{
    get { return (string)GetValue(CounterProperty); }
    set { SetValue(CounterProperty, value); }
}

我的班级:

private string _errorsCount;
public string ErrorsCount
{
    get { return _errorsCount; }
    set { _errorsCount = value; NotifyPropertyChanged("ErrorsCount"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (null != handler)
    {
      handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

所述用户控件的绑定:

dashboardCounter.Counter = view.ErrorsCount;

文本块显示 - 绝对没有。

我做错了什么?字符串是动态的,有时会更改。它最初是一个 Int,但我选择它作为字符串,并将我的"Count"转换为 String(),而不是创建一个 IValueConverter

通过使用dashboardCounter.Counter = view.ErrorsCount;,你只是调用依赖属性的setter,而依赖属性又调用DependencyProperty.SetValue方法。

这是它的官方描述(来自msdn):

设置依赖项属性的本地值,由其指定 依赖项属性标识符。

它设置本地值,仅此而已(当然,在此分配之后,您的绑定和文本块当然会更新)。

但是,Counter财产和ErrorsCount财产之间没有绑定创建。

因此,更新ErrorsCount不会更新Counter因此您的TextBlock也不会更新。

在您的示例中,当可能在初始化阶段调用dashboardCounter.Counter = view.ErrorsCount;时,Counter设置为 string.Emptynull(假设此时的值为 ErrorsCount),并将保持不变。不会创建绑定,更新ErrorsCount不会影响Counter或视图。

您至少有 3 种解决方案来解决您的问题:

1. 将您的Text属性直接绑定到实际更改的DependencyProperty或"INotifyPropertyChanged power属性"(最常见的情况)

2. 自己以编程方式创建所需的绑定,而不是使用 dashboardCounter.Counter = view.ErrorsCount; 。您将在此处找到一个简短的官方教程,代码可能如下所示:

 Binding yourbinding = new Binding("ErrorsCount");
 myBinding.Source = view;
 BindingOperations.SetBinding(dashboardCounter.nameofyourTextBlock, TextBlock.TextProperty, yourbinding);

3.当然,将您的ErrorsCount属性绑定到XAML中的Counter属性,但我不知道它是否符合您的需求:

<YourDashboardCounterControl Counter="{Binding Path=ErrorsCount Source=IfYouNeedIt}"

最新更新