Шаблон привязки в шаблоне управления
-
08-10-2019 - |
Вопрос
У меня есть следующий шаблон управления.
Я хочу установить свойство Source для контроля изображения в шаблоне управления с помощью привязки шаблона.
Но поскольку это шаблон управления для управления кнопкой, а элемент управления кнопки не имеет исходного свойства, я не могу использовать TemplateBinding в этом случае.
<ControlTemplate x:Key="BtnTemplate" TargetType="Button">
<Border CornerRadius="5" Margin="15" Cursor="Hand">
<StackPanel>
<Image Name="Img" Style="{StaticResource ImageStyle}" Source="temp.jpg" Height="100" Width="100" Margin="5"></Image>
<Label Content="{TemplateBinding Content}" Background="Transparent" Margin="2"></Label>
</StackPanel>
</Border>
</ControlTemplate>
Поскольку я должен установить разные изображения для разных экземпляров кнопки, я также не могу жесткокодировать путь.
Пожалуйста, дайте мне знать, как решать эту ситуацию.
Решение
Я предлагаю использовать динамические ресурсы, например, определите шаблон следующим образом:
<ControlTemplate x:Key="buttonTemplate" TargetType="Button">
<Border CornerRadius="5" Margin="15" Cursor="Hand">
<StackPanel Orientation="Horizontal" Background="Yellow">
<Image Source="{DynamicResource ResourceKey=Img}" Height="100" Width="100" Margin="5"></Image>
<Label Content="{TemplateBinding Content}" Background="Transparent" Margin="2"></Label>
</StackPanel>
</Border>
</ControlTemplate>
И использовать это так:
<Button Content="Button" Template="{StaticResource ResourceKey=buttonTemplate}">
<Button.Resources>
<ImageSource x:Key="Img">SomeUri.png/</ImageSource>
</Button.Resources>
</Button>
Другие советы
TemplateBinding - это легкая «привязка», оно не поддерживает некоторые особенности традиционного связывания, такого как автоматически введите преобразование, используя известные преобразователи типа, связанные с целевым свойством (например, преобразование строки URI в экземпляр BitmapSource).
Следующий код может работать должным образом:
<Window x:Class="GridScroll.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window2">
<Window.Resources>
<Style TargetType="{x:Type Button}" x:Key="ButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border CornerRadius="5" Margin="15" Cursor="Hand" Background="Red">
<StackPanel Orientation="Horizontal" Background="White">
<Image Name="Img" Source="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}" Margin="5"></Image>
<Label Content="{TemplateBinding Content}" Margin="2"></Label>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource ButtonStyle}" Tag="a.jpeg" Content="a"/>
<Button Style="{StaticResource ButtonStyle}" Tag="b.png" Content="b"/>
</StackPanel>
Вы действительно не сказали, как вы ожидаете, что потребители вашей кнопки установить источник. Вы могли бы использовать Button.Tag
Свойство, например, а затем связывается с этим в вашем шаблоне. Или вы можете определить свой собственный контроль:
public class ImageButton : Button
{
// add Source dependency property a la Image
}
А затем шаблон:
<ControlTemplate TargetType="ImageButton">
<Border CornerRadius="5" Margin="15" Cursor="Hand">
<StackPanel>
<Image Name="Img" Style="{StaticResource ImageStyle}" Source="{TempateBinding Source}" Height="100" Width="100" Margin="5"></Image>
<Label Content="{TemplateBinding Content}" Background="Transparent" Margin="2"></Label>
</StackPanel>
</Border>
</ControlTemplate>
Я не уверен, что я очень хорошо понял свою проблему, но почему бы вы не использовали ContentPresenter? Это позволяет переместить код для вашего изображения на более высоком уровне.
<ControlTemplate x:Key="BtnTemplate" TargetType="Button">
...
<ContentPresenter/>
</ControlTemplate>
...
<Button Template="{StaticResource BtnTemplate}">
<Image .../>
</Button>