2011-04-24 53 views
0

我有類標記模仿ItemsControl的行爲

class Marker { 
    public double Position {get; set;} 
    public string Label {get; set;} 
} 

和自定義控件等性質,公開標記

class MyControl { 
    public ObservableCollection<Marker> Markers {get; set;} 
} 

的集合,我想模仿ItemsControl的行爲,並允許我的組件的用戶直接或通過使用ItemsSource類比來指定標記。此外,我想這兩種方法使用MarkersSource

<my:MyControl MarkersSource={Binding UserSpecifiedCollection}"> 
</my:MyControl> 

第一種方法是非常簡單的,但我支持數據綁定(優選在XAML)

標記直接

<my:MyControl> 
    <my:MyControl.Markers> 
    <my:Marker Position="{Binding X}" /> 
    </my:MyControl.Markers> 
</my:MyControl> 

標記'正在與第二個掙扎。

我該如何實現MarkesSource?如何將UserSpecifiedCollection的項目轉換爲標記類型?如何將UserSpecifiedCollection項目的屬性綁定到Marker的屬性?

關於轉換我認爲可以使用ValueConvertor,但我更喜歡純粹的XAML解決方案,如DataTemplates。有可能的?

回答

0

您需要綁定的依賴項屬性,您可以通過使用DependencyProperty.AddOwner或僅創建自己的「回收」其他控件的屬性。此外,您可能希望將綁定從您的屬性「轉發」到內部ItemsControl或您使用的任何內容,例如

<UserControl x:Class="Test.UserControls.MyUserControl3" 
      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" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      Name="control"> 
    <Grid> 
     <!-- Binds to the new property --> 
     <ItemsControl ItemsSource="{Binding ElementName=control, Path=MarkersSource}"/> 
    </Grid> 
</UserControl> 
public partial class MyUserControl3 : UserControl 
{ 
    public static readonly DependencyProperty MarkersSourceProperty = 
      DependencyProperty.Register("MarkersSource", 
             typeof(ObservableCollection<Employee>), 
             typeof(MyUserControl3), 
             new UIPropertyMetadata(null)); 
    public ObservableCollection<Employee> MarkersSource 
    { 
     get { return (ObservableCollection<Employee>)GetValue(MarkersSourceProperty); } 
     set { SetValue(MarkersSourceProperty, value); } 
    } 

    public MyUserControl3() 
    { 
     InitializeComponent(); 
    } 
} 

用例:

<uc:MyUserControl3 MarkersSource="{Binding DpData}"> 
    <uc:MyUserControl3.Resources> 
     <DataTemplate DataType="{x:Type obj:Employee}"> 
      <TextBlock Text="{Binding Name}" Foreground="Red"/> 
     </DataTemplate> 
    </uc:MyUserControl3.Resources> 
</uc:MyUserControl3> 

在這裏,我含蓄地申請通過資源DataTemplate中,但你可以創建另一個屬性(重用ItemsControl.ItemTemplate),並轉發到內部ItemsControl的。

+0

語法高亮取決於問題上的標記。 – 2011-04-25 02:20:24

+0

@Rick Sladkey:所以我聽說過;它肯定會很好,如果它會比這更聰明一些... – 2011-04-25 02:55:22

+0

對我而言,這是一個愚蠢的行爲,有時候它的表現會有所不同。 – 2011-04-25 02:58:13

相關問題