2

我有我的自定義用戶控件一個DependencyProperty,看起來像這樣:如何綁定到此自定義依賴項屬性?

public static readonly DependencyProperty ColumnWidthProperty = 
    DependencyProperty.Register("ColumnWidth", typeof(int), typeof(CallBoard), 
     new PropertyMetadata(150)); 

public int ColumnWidth { 
    get { return (int)GetValue(ColumnWidthProperty); } 
    set { SetValue(ColumnWidthProperty, value); } 
} 

在Expression Blend 3,我有這樣的:

<UserControl 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    x:Class="SilverlightTest.CallBoard" 
    d:DesignWidth="640" d:DesignHeight="480"> 
    <UserControl.Resources> 
     <DataTemplate x:Key="EmployeeHeaderTemplate"> 
      <TextBlock Text="{Binding Name}" TextAlignment="Center" FontWeight="Bold" FontSize="16"/> 
     </DataTemplate> 
     <DataTemplate x:Key="CallListItemTemplate"> 
      <StackPanel > 
       <TextBlock Text="{Binding CustomerName}" FontWeight="Bold"/> 
       <TextBlock Text="{Binding Details}"/> 
      </StackPanel> 
     </DataTemplate> 
     <DataTemplate x:Key="CallListTemplate"> 
      <ListBox ItemTemplate="{StaticResource CallListItemTemplate}" ItemsSource="{Binding Calls}"/> 
     </DataTemplate> 
    </UserControl.Resources> 
    <StackPanel x:Name="stackPanel" DataContext="{Binding Source={StaticResource DummyDataSource}}"> 
     <ItemsControl ItemsPanel="{StaticResource HorizontalItemsPanelTemplate}" ItemTemplate="{StaticResource EmployeeHeaderTemplate}" ItemsSource="{Binding}"/> 
     <ItemsControl ItemsPanel="{StaticResource HorizontalItemsPanelTemplate}" ItemTemplate="{StaticResource CallListTemplate}" ItemsSource="{Binding}"/> 
    </StackPanel> 
</UserControl> 

現在,我希望做的是使ColumnWidth依賴項屬性控制EmployeeHeaderTemplate DataTemplate中的TextBlock和CallListTemplate DataTemplate中的ListBox的寬度。我知道我可以在C#中做到這一點,但我有一種感覺,它也可以使用純XAML數據綁定。

但是,Silverlight和Expression Blend 3相對來說比較新,我不確定如何去做這件事。有什麼建議麼?

回答

1

嘗試在您的CallBoard實例上放置一個名稱,然後在您的綁定中引用使用ElementName的名稱。

所以你的頁面的根會是什麼樣子:

<UserControl 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     x:Class="SilverlightTest.CallBoard" 
     x:Name="callBoard" 
     ... 
    > 
    ... 

和你的綁定將如下所示:

Width="{Binding ElementName=callBoard, Path=ColumnWidth}" 
+0

該方法的問題是我將無法在同一頁上使用該控件的多個實例。我只是決定在代碼隱藏文件中進行綁定。 – 2009-09-09 02:00:13

0

Width="{Binding ColumnWidth}"不工作?

+0

它不會出現。 – 2009-09-06 01:32:45