如何绑定到此自定义依赖项属性?

问题描述:

我有我的自定义用户控件一个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相对来说比较新,我不确定如何去做这件事。有什么建议么?

尝试在您的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

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

+0

它不会出现。 – 2009-09-06 01:32:45