2013-04-16 3 views
0

CustomLabel String이라는 종속성 속성을 사용하여 UserControl을 만들었습니다.XAML에서 사용자 지정 속성에 액세스하는 방법

컨트롤에는 CustomLabel 속성 값을 표시해야하는 Label이 포함되어 있습니다.

... 
<Label Content="{Binding ...point to the Label property... }"/> 
... 

하지만 노력 많은 조합 : 내가 XAML에서 쉬운 방법, 뭔가가 있어야합니다 알고

public class MyControl : UserControl 
{ 
    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
     "Label", 
     typeof(String), 
     typeof(ProjectionControl), 
     new FrameworkPropertyMetadata("FLAT", OnLabelPropertyChanged)); 

    private static void OnLabelPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs eventArgs) 
    { 
     ((Label)FindName("myLabel")).Content = (string)GetValue("LabelProperty"); 
    } 
} 

:

내가 사용하는 코드에서이 작업을 수행 할 수 있습니다 이벤트 핸들러를 OnLabelPropertyChanged (RelativeSource/Pah, Source/Path, x : Reference, 방금 속성 이름 쓰기 ...) 아무 것도 작동하지 않았습니다 ...

나는 exper입니다. WinForms에서 WPF를 배우고 WPF를 약간의 시간 동안 배우지 만 이러한 것들은 여전히 ​​나에게 외계인입니다.

+0

당신은'{TemplateBinding}'을 사용해야합니다. 방법을 알려줄 수 있도록 컨트롤의 전체 XAML을 게시하십시오. –

답변

2

당신은 단지 Label 특성 또한

<Label Content="{Binding Label}"/> 

에 바인딩 할 수 있습니다 당신은 당신의 xaml

<UserControl x:Class="WpfApplication10.MyUserControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      Name="UI"> // Set a name 

    <Grid DataContext="{Binding ElementName=UI}"> //Set DataContext using the name of the UserControl 
     <Label Content="{Binding Label}" /> 
    </Grid> 
</UserControl> 

전체 예에 UserControlDataContext을 설정 할 수 있습니다 :

코드 :

,210

XAML :

<UserControl x:Class="WpfApplication10.MyUserControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      Name="UI"> 

    <Grid DataContext="{Binding ElementName=UI}"> 
     <TextBlock Text="{Binding Label}" /> 
    </Grid> 
</UserControl> 
+0

감사! ElementName 매개 변수와 사용자 정의 컨트롤의 이름이 트릭입니다. – Libor

+0

고마워, 맞아. 하지만 왜 그렇게 복잡해야합니까? – Peter

관련 문제