2013-10-31 178 views
2

我有一个自定义用户控件,其中的文本有时会更改文本块。 的代码的TextBlocks是自定义用户控件TextBlock.text绑定

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; 

TextBlock显示 - 绝对没有。

我做错了什么? 字符串是动态的,有时会发生变化。 它最初的诠释,但我选择了它是字符串,而不是和转换,而不是创建的IValueConverter

+0

难道说的ElementName值是区分大小写和一个C少校在失踪你的绑定:“ElementName = dashboardcounter”? – AirL

+0

x:Name =“dashboardcounter” - 那不是它 – VisualBean

+0

它工作,如果我设置“计数器”目录dashboardCounter.Counter =“sometext”; – VisualBean

回答

2

使用dashboardCounter.Counter = view.ErrorsCount;你只是叫你所依赖的setter方法,我的“伯爵”的toString(),后者又调用DependencyProperty.SetValue方法。

下面是它(从MSDN)的官方说明:

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

它设置本地值,这就是全部(当然,在这个任务之后,当然你的绑定和你的文本块会被更新)。

但您的Counter属性和您的ErrorsCount属性之间没有绑定。

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

在你的榜样,当dashboardCounter.Counter = view.ErrorsCount;是在初始化阶段大概叫,Counter设置为string.Emptynull(假设在这一点上的ErrorsCount这个值),并会保持不变。没有创建绑定,更新ErrorsCount不会影响Counter或您的视图。

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

。直接在Text属性绑定到DependencyProperty或“INotifyPropertyChanged动力性能”,实际上是不断变化的(最常见的情况)

。以编程方式自己创建所需的绑定,而不是使用dashboardCounter.Counter = view.ErrorsCount;。你会在here找到一个简短的教程官方和代码会像下面的一个:

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

。当然,你ErrorsCount属性绑定在XAML你Counter属性,但我不知道这是否会适合您的需要:

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