C# 自定义Usercontrol TextBlock.text绑定

C# 自定义Usercontrol TextBlock.text绑定,c#,wpf,xaml,binding,user-controls,C#,Wpf,Xaml,Binding,User Controls,我有一个自定义用户控件,它有一个文本块,其文本有时会更改。 TextBlocks代码是 XAML: 我的班级: private string _errorsCount; public string ErrorsCount { get { return _errorsCount; } set { _errorsCount = value; NotifyPropertyChanged("ErrorsCount"); } } public event PropertyChangedE

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

XAML:

我的班级:

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,但我选择它作为string,并将我的“Count”转换为string(),而不是使用
dashboardCounter.Counter=view.errorscont创建一个IValueConverter

您只是在调用依赖项属性的setter,而setter又反过来调用该方法

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

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

它设置本地值,仅此而已(当然,在此赋值之后,您的绑定和文本块将被更新)

但是在
计数器
属性和
errorscont
属性之间没有绑定创建

因此,更新
errorscont
不会更新
计数器
,因此您的
TextBlock
也不会更新

在您的示例中,当
dashboardCounter.Counter=view.errorscont
可能在初始化阶段调用,
计数器
设置为
字符串。空
(假设该值为
ERRORSONT
),并且将保持不变。没有创建绑定,更新
errorscont
不会影响
计数器
或您的视图

您至少有3种解决方案:

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

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

 Binding yourbinding = new Binding("ErrorsCount");
 myBinding.Source = view;
 BindingOperations.SetBinding(dashboardCounter.nameofyourTextBlock, TextBlock.TextProperty, yourbinding);
3。当然,将
errorscont
属性绑定到XAML中的
Counter
属性,但我不知道它是否适合您的需要:

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

是否可能是ElementName值区分大小写,并且绑定中缺少一个C maj:“ElementName=dashboardcounter”?x:Name=“dashboardcounter”-这不是问题如果我设置“counter”目录dashboardcounter.counter=“sometext”;使用dashboardCounter.Counter=view.ErrorsCount;您是否正在尝试将代码隐藏依赖项属性绑定到类属性?所以当ErrorScont被更新时,它会通知并更新计数器,而计数器又会通知视图/绑定?
 Binding yourbinding = new Binding("ErrorsCount");
 myBinding.Source = view;
 BindingOperations.SetBinding(dashboardCounter.nameofyourTextBlock, TextBlock.TextProperty, yourbinding);
<YourDashboardCounterControl Counter="{Binding Path=ErrorsCount Source=IfYouNeedIt}"