2013-10-31 3 views
2

텍스트가 때때로 변경되는 텍스트 블록이있는 사용자 지정 사용자 정의 컨트롤이 있습니다.사용자 지정 Usercontrol TextBlock.text 바인딩

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

바인딩의 말 UserControl을 :

dashboardCounter.Counter = view.ErrorsCount; 
01 TextBlocks 코드

XAML입니다

TextBlock은 절대적으로 아무것도 표시하지 않습니다.

무엇이 잘못 되었나요? 문자열이 동적이며 경우에 따라 변경됩니다. 그것은 원래 지능했지만, 난 대신 문자열 대신 당신은 당신의 종속성 속성의 세터를 호출하는 dashboardCounter.Counter = view.ErrorsCount;를 사용하여 IValueConverter

+0

그것이 ElementName에 값이 대소 문자를 구별하는 것이 될 수 있고 바인딩 : "ElementName = dashboardcounter"? – AirL

+0

x : Name = "dashboardcounter"- 그게 아니라 – VisualBean

+0

"counter"디렉토리를 설정하면 작동합니다. dashboardCounter.Counter = "sometext"; – VisualBean

답변

2

을 만드는) 내 "카운트"toString을 (전환하기로 결정했습니다 차례로 호출에 DependencyProperty.SetValue 방법.

여기 (MSDN)에서 그것의 공식 설명이다 :

는 종속성 속성 식별자로 지정되는 종속성 속성의 로컬 값을 설정.

로컬 값을 설정합니다. 물론이 할당에 따라 바인딩과 텍스트 블록이 업데이트됩니다.

하지만 Counter 속성과 ErrorsCount 속성 사이에는 바인딩 만들기가 없습니다.

따라서 ErrorsCount을 업데이트하면 Counter가 업데이트되지 않으므로 TextBlock도 업데이트되지 않습니다. dashboardCounter.Counter = view.ErrorsCount;가 초기화 단계에서 아마라고 당신의 예에서

, Counter은 (그 시점에서 ErrorsCount의 이것을 값을 가정) string.Empty 또는 null로 설정되고 변경되지 않습니다. 바인딩이 생성되지 않아 ErrorsCount을 업데이트해도 Counter 또는보기에는 영향을주지 않습니다.

1 :

당신은 당신의 문제를 해결하기 위해 3 개 이상의 솔루션을 가지고있다. 직접 DependencyProperty 또는 실제로 변경되는 "INotifyPropertyChanged 전원 특성"(가장 일반적인 경우)

2Text 속성을 바인딩합니다. dashboardCounter.Counter = view.ErrorsCount; 대신 직접 프로그래밍 방식으로 필요한 바인딩을 만듭니다.당신은 here 짧은 공식 자습서를 찾을 수 있습니다 및 코드는 다음과 하나로 볼 수 있었다 :

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

3을. 그리고 물론, XAML에서 Counter 재산에 ErrorsCount 속성을 결합하지만 난 그것이 당신의 요구에 맞게 것이다 알고하지 않습니다는 C 소령이 누락되어

<YourDashboardCounterControl Counter="{Binding Path=ErrorsCount Source=IfYouNeedIt}" 
관련 문제