0

我有课标记

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

和自定义控件,除其他属性外,还公开标记集合

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

我想模仿 ItemsControl 行为并允许我的组件的用户直接或通过使用 ItemsSource 类比来指定标记。此外,我希望这两种方法都支持数据绑定(最好在 XAML 中)

直接标记

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

使用 MarkersSource 的标记

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

第一种方法非常简单,但我正在为第二种方法苦苦挣扎。

如何实现 MarkesSource?如何将 UserSpecifiedCollection 的项目转换为 Marker 类型?UserSpecifiedCollection 项的属性如何数据绑定到 Marker 的属性?

关于转换,我认为可以使用 ValueConvertor,但我更喜欢纯 XAML 解决方案,比如 DataTemplates。有可能的?

4

1 回答 1

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。

于 2011-04-25T01:18:12.873 回答