Как прикрепить свойство к объекту с помощью XAML - PullRequest
0 голосов
/ 02 января 2012

Я пытаюсь отформатировать свой шаблон ListBoxItem, чтобы включить изображение.Я могу добавить изображение в ListBoxItem, но я не совсем уверен, как бы я мог установить значение для этого изображения.

Шаблон для ListBoxItem:

        <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Border Name="Border" Padding="2" SnapsToDevicePixels="true">
                        <StackPanel Orientation="Horizontal" >
                            <Image Source="{Binding Path=Source}" Height="16" Width="16" HorizontalAlignment="Center" VerticalAlignment="Center" />
                            <ContentPresenter Name="ContentPresenter" HorizontalAlignment="Stretch" Width="Auto" />
                        </StackPanel>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter TargetName="Border" Property="Background" Value="{StaticResource ListBoxItem_BackgroundBrush_Selected}"/>
                            <Setter TargetName="ContentPresenter" Property="TextElement.FontWeight" Value="Bold"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{StaticResource TabItem_BackgroundBrush_Disabled}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Пример кода ListBox:

   <ListBox Name="listBox_LibAll" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
       <ListBoxItem Content="Item 1" />
       <ListBoxItem Content="Item 2" />
       <ListBoxItem Content="Item 3" />                                
   </ListBox>

Вывод: enter image description here

Если вы посмотрите на картинку, вы заметите, что для изображения есть место, я просто не знаю, как установить его значение.Я думал, что мог бы как-то присоединить свойство «Source» к ListBoxItem

Ответы [ 2 ]

2 голосов
/ 02 января 2012

Вы можете сделать привязку RelativeSource к Tag или некоторому присоединенному свойству .

Source="{Binding Tag, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"

<ListBoxItem Tag="SomePath" />
Source="{Binding (ns:AttachedProperties.Source), RelativeSource={RelativeSource AncestorType=ListBoxItem}}"

<ListBoxItem ns:AttachedProperties.Source="SomePath" />

Вы также можете использовать динамические ресурсы, как показано здесь .

Однако самое чистое решение - сделать контент сложным, то есть сделать хост ListBoxItem UserControl или пользовательский элемент управления, например, который на самом деле имеет правильное свойство для изображения. Обычно вам не следует переопределять шаблон управления ListBoxItems, а использовать ItemTemplate ListBox для шаблона данных данных.

0 голосов
/ 02 января 2012

Вы были почти там.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class ImageItem: DependencyObject
    {
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.RegisterAttached("Source",
            typeof(string),
            typeof(DependencyObject),
            new PropertyMetadata((o, e) => 
            {
                //System.Diagnostics.Debugger.Break();
            }));

        public static string GetSource(DependencyObject o)
        {
            return (string)o.GetValue(ImageItem.SourceProperty);
        }

        public static void SetSource(DependencyObject o, string e)
        {
            o.SetValue(ImageItem.SourceProperty, e);
        }
    }
}

Markup:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Border Name="Border" Padding="2" SnapsToDevicePixels="true">
                                <StackPanel Orientation="Horizontal" >
                                    <Image Source="{Binding Path=Source, 
                                           RelativeSource={RelativeSource AncestorType=ListBoxItem}}" 
                                           Height="16" 
                                           Width="16" 
                                           HorizontalAlignment="Center" VerticalAlignment="Center" />
                                    <ContentPresenter Name="ContentPresenter" HorizontalAlignment="Stretch" Width="Auto" />
                                </StackPanel>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsSelected" Value="true">
                                    <Setter TargetName="Border" Property="Background" Value="{StaticResource ListBoxItem_BackgroundBrush_Selected}"/>
                                    <Setter TargetName="ContentPresenter" Property="TextElement.FontWeight" Value="Bold"/>
                                </Trigger>
                                <Trigger Property="IsEnabled" Value="false">
                                    <Setter Property="Foreground" Value="{StaticResource TabItem_BackgroundBrush_Disabled}"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Grid.Resources>
        <ListBox Name="listBox_LibAll" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <ListBoxItem local:ImageItem.Source="/WpfApplication1;component/Penguins.jpg" Content="Item 1" />
            <ListBoxItem Content="Item 2" />
            <ListBoxItem Content="Item 3" />
        </ListBox>
    </Grid>
</Window>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...