[英]Attached properties in Template WPF XAML
我已使用附加屬性附加屬性和ControlTemplate。 附加屬性:
using System.Windows;
namespace NoteProjectV2.classes.frmtopicclasses
{
class togglebuttonimage : DependencyObject
{
public static readonly DependencyProperty togglebuttonimagesource = DependencyProperty.RegisterAttached("ImageSource", typeof(string), typeof(togglebuttonimage), new PropertyMetadata(default(string)));
public static void Settogglebuttonimagesource(UIElement element, string value)
{
element.SetValue(togglebuttonimagesource, value);
}
public static string Gettogglebuttonimagesource(UIElement element)
{
return (string)element.GetValue(togglebuttonimagesource);
}
}
}
這是我的控制模板(我在切換按鈕中使用了它)
<Application x:Class="NoteProjectV2.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:NoteProjectV2"
xmlns:m="clr-namespace:NoteProjectV2.classes.frmtopicclasses"
StartupUri="frmTopic.xaml">
<Application.Resources>
<Style x:Key="togglebutton_topic_menu_normal" TargetType="ToggleButton">
<Setter Property="Width" Value="40" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border Name="border">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Black"/>
</Style>
</Border.Style>
<Image Width="22" Height="22" Name="image" >
<Image.Style>
<Style>
Only This is not working===============> <Setter Property="Image.Source" Value="{Binding Path=(m:togglebuttonimage.togglebuttonimagesource),RelativeSource={RelativeSource TemplatedParent}}" />
</Style>
</Image.Style>
</Image>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
我在代碼中使用了附加屬性:我還在上面添加了名稱空間
xmlns:m="clr-namespace:NoteProjectV2.classes.frmtopicclasses"
<ToggleButton Style="{StaticResource togglebutton_topic_menu_normal}" m:togglebuttonimage.togglebuttonimagesource="accept.png" />
但這不起作用我的問題在哪里?
類DependencyProperty的Register
和RegisterAttached
方法的第一個參數是屬性的名稱。
當您使用名稱"ImageSource"
,它實際上應該是"ToggleButtonImageSource"
(它已經使用了正確的大小寫)。 還要注意,只要僅聲明附加屬性,就不必從DependencyObject派生擁有的類。
public class ToggleButtonImage
{
public static readonly DependencyProperty ToggleButtonImageSourceProperty =
DependencyProperty.RegisterAttached(
"ToggleButtonImageSource", typeof(string), typeof(ToggleButtonImage));
public static void SetToggleButtonImageSource(UIElement element, string value)
{
element.SetValue(ToggleButtonImageSourceProperty, value);
}
public static string GetToggleButtonImageSource(UIElement element)
{
return (string)element.GetValue(ToggleButtonImageSourceProperty);
}
}
除此之外,您最好使用ImageSource
而不是string
作為屬性的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.