2013-04-16 21 views
0

訪問自定義屬性已經創建了一個名爲String類型的CustomLabel依賴屬性一個用戶控件。我如何在XAML

該控件包含標籤,該標籤應該顯示值CustomLabel屬性。

我可以在代碼中使用做到這一點OnLabelPropertyChanged事件處理程序:

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

我知道必須有XAML更簡單的方法,是這樣的:

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

但我已經嘗試了多種組合(的RelativeSource /呸,源/路徑,X:參考,只是寫屬性名稱...)並沒有什麼工作......

我EXPER在WinForms上學習WPF並學習一些Thime,但這些東西對我來說依然是陌生的。

+0

你必須使用一個'{TemplateBinding}'。發佈完整的XAML控件,以便我可以告訴你如何。 –

回答

2

您可以直接綁定到Label財產

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

你也可能需要設置DataContextUserControlxaml

<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> 

完整的例子:

代碼:

public partial class MyUserControl : UserControl 
{ 
    public MyUserControl() 
    { 
     InitializeComponent(); 
    } 

    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
     "Label", typeof(String),typeof(MyUserControl), new FrameworkPropertyMetadata("FLAT")); 

    public string Label 
    { 
     get { return (string)GetValue(LabelProperty); } 
     set { SetValue(LabelProperty, value); } 
    } 
} 

的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