DependencyProperty для коллекции кнопок - PullRequest
1 голос
/ 17 апреля 2019

Я хочу дать пользователю возможность установить набор кнопок в моем CustomControl.

Я пытался решить эту проблему с помощью ItemsControl следующим образом:

<ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type cc:MyCustomControl}}, Path=Buttons}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Command="{Binding Command}">
                <Image Source="{Binding MyImageSource}"/>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Кнопки DependencyProperty:

public static readonly DependencyProperty ButtonsProperty = DependencyProperty.Register(
    "Buttons", typeof(IList), typeof(TileGrid), new PropertyMetadata(default(IList)));

public IList Buttons
{
    get { return (IList) GetValue(ButtonsProperty); }
    set { SetValue(ButtonsProperty, value); }
}

Класс MyButton:

public class MyButton: Button
{
    public ImageSource MyImageSource { get; set; }
}

И как я хочу видеть это в реализации CustomControl:

<cc:MyCustomControl>
    <cc:MyCustomControl.Buttons>
        <cc:MyButton Command="{Binding SignDocumentsCommand}"
                     MyImageSource="pack://application:,,,/CommonResources;component/Images/Icons/pen.png"/>

        <cc:MyButton Command="{Binding DeleteDocumentsCommand}"
                     MyImageSource="pack://application:,,,/CommonResources;component/Images/Icons/remove.png"/>
    </cc:MyCustomControl.Buttons>
</cc:MyCustomControl>

Но это не работает.В живом визуальном дереве я вижу только MyButtons внутри ItemsControl.Это правильный подход?Или мне нужно решить это по-другому?

1 Ответ

1 голос
/ 17 апреля 2019

Тип, который вы используете для элементов Button в ItemsControl, не должен быть производным от Button.Вы можете использовать что-то простое, как показано ниже.Также необязательно объявлять свойство Buttons как свойство зависимости.Достаточно простой ObservableCollection.

public class MyButtonItem : DependencyObject
{
    public static DependencyProperty CommandProperty = DependencyProperty.Register(
        nameof(Command), typeof(ICommand), typeof(MyButtonItem));

    public static DependencyProperty ImageSourceProperty = DependencyProperty.Register(
        nameof(ImageSource), typeof(ImageSource), typeof(MyButtonItem));

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public ImageSource ImageSource
    {
        get { return (ImageSource)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }
}

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

    public ObservableCollection<MyButtonItem> Buttons { get; }
        = new ObservableCollection<MyButtonItem>();
}

Элементы управления XAML будут такими же, как у вас:

<ItemsControl ItemsSource="{Binding Buttons,
                  RelativeSource={RelativeSource AncestorType=UserControl}}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Command="{Binding Command}">
                <Image Source="{Binding ImageSource}"/>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Затем вы добавите объекты MyButtonItem в коллекцию Buttons:

<cc:MyCustomControl>
    <cc:MyCustomControl.Buttons>

        <cc:MyButtonItem
            Command="{Binding SignDocumentsCommand}"
            ImageSource="/CommonResources;component/Images/Icons/pen.png"/>

        <cc:MyButtonItem
            Command="{Binding DeleteDocumentsCommand}"
            ImageSource="/CommonResources;component/Images/Icons/remove.png"/>

    </cc:MyCustomControl.Buttons>
</cc:MyCustomControl>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...