2011-11-27 1 views
3

ToggleSwitch 및 TextBlock이 포함 된 ToggleSwitchItem 사용자 정의 컨트롤을 만들고 있습니다. 개인 ToggleSwitch 자식의 IsChecked 속성을 노출하는 데 사용하려는 IsChecked라는 종속성 속성을 정의했습니다.자식 중 하나에서 값을 버블 링하는 사용자 정의 컨트롤에서 종속성 속성을 정의하는 방법은 무엇입니까?

그러나 데이터 바인딩이 작동하지 않습니다 ...로드 될 때 기본값으로 유지됩니다.

무엇이 누락 되었습니까?

코드 : 데이터 바인딩에 대한

public static readonly DependencyProperty IsCheckedProperty = 
    DependencyProperty.Register(
     "IsChecked", 
     typeof(bool), 
     typeof(ToggleSwitchItem), 
     new PropertyMetadata(new PropertyChangedCallback 
      (OnIsCheckedChanged))); 

public bool IsChecked 
{ 
    get 
    { 
    return (bool)GetValue(IsCheckedProperty); 
    } 
    set 
    { 
    SetValue(IsCheckedProperty, value); 
    } 
} 

private static void OnIsCheckedChanged(DependencyObject d, 
    DependencyPropertyChangedEventArgs e) 
{ 
    ToggleSwitchItem item = (ToggleSwitchItem)d; 
    bool newValue = (bool)e.NewValue; 
    item.m_switch.IsChecked = newValue; 
} 

, 나는 다음에 사용하고 있습니다 : 일반 바닐라에 바인딩 할 때이 문제없이 작동으로

<phone:PhoneApplicationPage.Resources> 
    <myApp:SharedPreferences x:Key="appSettings"/> 
</phone:PhoneApplicationPage.Resources> 

IsChecked="{Binding Source={StaticResource appSettings}, 
    Path=SomeProperty, Mode=TwoWay}" 

된 SharedPreferences 클래스는, 잘 작동 위와 동일하게 스위치의 IsChecked 속성을 토글합니다.

감사합니다.


솔루션 (안토니의 도움으로) :

내가 지금처럼 사용자 정의 컨트롤의 생성자에서 내 사용자 컨트롤에 내 아이 토글 스위치를 결합 :

Binding binding = new Binding(); 
binding.Source = this; 
binding.Path = new PropertyPath("IsChecked"); 
binding.Mode = BindingMode.TwoWay; 
m_switch.SetBinding(ToggleSwitch.IsCheckedProperty, binding); 

그리고 나는 제거 더 이상 필요하지 않은 콜백 :

public static readonly DependencyProperty IsCheckedProperty = 
    DependencyProperty.Register(
     "IsChecked", 
     typeof(bool), 
     typeof(ToggleSwitchItem), 
     null); 

public bool IsChecked 
{ 
    get 
    { 
    return (bool)GetValue(IsCheckedProperty); 
    } 
    set 
    { 
    SetValue(IsCheckedProperty, value); 
    } 
} 
+0

감사합니다 도움이 될 수. 순수한 XAML에서 바인딩을 사용하면 문제가 발생했습니다. 뒤에 코드에서 바인딩을 설정할 때만 작동합니다. – t9mike

답변

2

사용자가 스위치를 전환하는 방법이 실제로 IsChecked 속성을 변경하게하는 방법을 보여주지 않았다는 것을 제외하고는 지금까지 보여준 코드에 실제로 잘못된 것이 무엇인지 알 수 없습니다.

<ToggleButton IsChecked="{Binding Parent.IsChecked, ElementName=LayoutRoot, Mode=TwoWay}" /> 

당신은이 방법과 OnPropertyChanged를 콜백을 필요가 없습니다

당신이 UserControl 내부 바인딩을 사용 보라고.

+0

굉장!이 작품! 고마워. 내가 코드 비하인드에서 할 필요가 있다는 것을 제외하고. 코드 질문 코드로 위 질문에 업데이 트되었습니다. – swinefeaster

+0

또한 사용자 정의 컨트롤의 생성자에'LayoutRoot'의'DataContext'를 설정할 수 있습니다 : xaml에서'Parent' 및'LayoutRoot' 선언을 생략 할 수 있습니다 : ' saxos

1

체 ck 컨트롤의 DataContext. 두 가지 의미 : 컨트롤의 모든 인스턴스를 올바른 DataContext -ok-, 작업 할 수 있어야합니다 및 또한 (클래스 수준에서) 컨트롤을 정의 할 때이 DataContext 휴식해야합니다. 컨트롤을 정의 할 때 DataContext를 'this'/ Me 나 'xaml'의 'Self'로 설정하면 해당 속성은 자신을 참조하고 응용 프로그램에서 인스턴스화 할 때 DataContext를 잊어 버립니다 바인딩이 실패합니다.

컨트롤 Xaml에서 컨트롤의 속성을 참조해야하는 경우 findAncestor/AncestorType = ToggleSwitchItem과 바인딩을 사용하거나 Xaml에서 컨트롤의 이름을 지정하고 해당 ElementName으로 바인딩하십시오.

+0

내가 당신을 팔로우하는지 확실하지 않습니다. 바인딩 xaml 추가 및 위의 질문에 대한 자세한 내용은이 명확하게 희망? – swinefeaster

+0

나는 분명히하려고 애썼다. – GameAlchemist

+0

지금은 분명합니까?나는 Xaml을 당신의 통제하에 두는 것이 더 따뜻합니까? 아니면 그것의 인스턴스에서 ?? 컨트롤의 Xaml 인 경우 응용 프로그램에서 사용중인 인스턴스에 아무 것도 수행하지 않는 AppSettings의 인스턴스 *에 바인딩되어 있기 때문입니다. – GameAlchemist

0

어쩌면이에 대한

public bool IsChecked 
    { 
     get { return GetValue(IsCheckedProperty) is bool ? (bool) GetValue(IsCheckedProperty) : false; } 
     set 
     { 
      SetValue(IsCheckedProperty, value); 
     } 
    } 
관련 문제