0
我有附加屬性和ControlTemplate使用附加的屬性。 附加屬性格式:模板中的附加屬性WPF XAML
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" />
但命名空間這不起作用我的問題在哪裏?
您不遵循依賴項屬性的命名約定。請看看[這裏在SO](http://stackoverflow.com/questions/7139641/how-to-use-attached-property-within-a-style) – gomi42
你肯定同意'togglebuttonimagesource'是一個可怕的一個屬性的名稱,更不用說方法名稱lile'Settogglebuttonimagesource'。改用[Pascal Casing](https://msdn.microsoft.com/en-us/library/ms229043(v = vs.110).aspx)。 – Clemens