我使用附加属性附加了Property和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);
}
}
}
这是我的控件模板(我在togglebutton中使用过它)
<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>
我在代码中使用了附加的propery:我还在上面添加了命名空间
xmlns:m="clr-namespace:NoteProjectV2.classes.frmtopicclasses"
<ToggleButton Style="{StaticResource togglebutton_topic_menu_normal}" m:togglebuttonimage.togglebuttonimagesource="accept.png" />
但这不起作用我的问题在哪里?
答案 0 :(得分:1)
类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
作为属性的类型。