2013-10-31 176 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}"