c# - 自定义用户控件 TextBlock.text 绑定(bind)

标签 c# wpf xaml binding user-controls

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

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

我的类(class):

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

所述用户控件的绑定(bind):

dashboardCounter.Counter = view.ErrorsCount;

TextBlock 显示 - 绝对没有。

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

最佳答案

通过使用 dashboardCounter.Counter = view.ErrorsCount;,您只需调用依赖项属性的 setter,该属性又会调用 DependencyProperty.SetValue方法。

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

Sets the local value of a dependency property, specified by its dependency property identifier.

它设置了本地值,仅此而已(当然,在这个分配之后,您的绑定(bind)和文本 block 将被更新)。

但是 Counter 属性和 ErrorsCount 属性之间没有创建绑定(bind)。

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

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

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

1。将您的 Text 属性直接绑定(bind)到实际更改的 DependencyProperty 或“INotifyPropertyChanged 支持的属性”(最常见的情况)

2。自行以编程方式创建所需的绑定(bind),而不是使用 dashboardCounter.Counter = view.ErrorsCount;。您可以在 here 中找到简短的官方教程。代码可能如下所示:

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

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

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

关于c# - 自定义用户控件 TextBlock.text 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19718364/

相关文章:

wpf - 根据 Visual Studio 主题的变化更改图标

c# - 跨组件的持续管理

wpf - 如何避免使用 WPF 进行抗锯齿?

c# - 在 tabitems 中加载列表框 - 使用哪个事件?

wpf - XmlDataProvider具有未显式设置其XmlNamespace的内联XML

c# - 绑定(bind)Command时绑定(bind)IsEnabled是可选的吗?

c# - 获取 UAP10 平台上加载的程序集列表

c# - 从 TimerCallback 引用 Threading.Timer 是否使其免受 GC 的影响

c# - 无法获取名为 MySql.Data.MySqlClient 的数据提供程序的提供程序工厂

c# - WPF - 根据附加属性的值重用具有不同设置的 UserControl