C# 具有自定义属性的用户控件
我正在尝试创建一个UserControl,它是一个图表项的图例, 我已经定义了它,所以它有一个带有图形名称的标签,一个复选框 定义是否显示它,以及一个带有图形颜色的矩形 xaml的定义如下:C# 具有自定义属性的用户控件,c#,wpf,xaml,user-controls,wpf-controls,C#,Wpf,Xaml,User Controls,Wpf Controls,我正在尝试创建一个UserControl,它是一个图表项的图例, 我已经定义了它,所以它有一个带有图形名称的标签,一个复选框 定义是否显示它,以及一个带有图形颜色的矩形 xaml的定义如下: <UserControl x:Class="Resources.LegendItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http:/
<UserControl x:Class="Resources.LegendItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<UserControl.Template>
<ControlTemplate>
<StackPanel Margin="1,0,0,0" Orientation="Horizontal">
<CheckBox Name="cb" IsChecked="{TemplateBinding IsGraphVisible}" >
<StackPanel Margin="1,0,0,0" Orientation="Horizontal">
<Rectangle Name="rec" RadiusX="2" RadiusY="2" Height="10" Width="10" />
<Label Name="lab" Content="{TemplateBinding GraphName}" />
</StackPanel>
</CheckBox>
</StackPanel>
</ControlTemplate>
</UserControl.Template>
</UserControl>
但是当我编译它时,我得到一个错误“在类型“Control”上找不到静态成员“IsGraphVisibleProperty”
任何帮助都将不胜感激。您需要在
ControlTemplate
上指定TargetType=“{x:Type Resources.LegendItem}”
,否则它默认为控件的模板,您将收到该错误。您根本不需要模板UserControl
允许直接声明XAML。无法在用户控件中设置模板:
<UserControl x:Class="Resources.LegendItem" x:Name="MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<StackPanel Margin="1,0,0,0" Orientation="Horizontal">
<CheckBox Name="cb" IsChecked="{Binding ElementName=MyControl, Path=IsGraphVisible}" >
<StackPanel Margin="1,0,0,0" Orientation="Horizontal">
<Rectangle Name="rec" RadiusX="2" RadiusY="2" Height="10" Width="10" />
<Label Name="lab" Content="{Binding ElementName=MyControl, Path=GraphName}" />
</StackPanel>
</CheckBox>
</StackPanel>
</UserControl>
顺便问一下,为什么它是控件的模板而不是用户控件?因为控件是可以模板化的最通用控件。模板属性首先出现在控件中。UserControls不允许设置模板。
<UserControl x:Class="Resources.LegendItem" x:Name="MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<StackPanel Margin="1,0,0,0" Orientation="Horizontal">
<CheckBox Name="cb" IsChecked="{Binding ElementName=MyControl, Path=IsGraphVisible}" >
<StackPanel Margin="1,0,0,0" Orientation="Horizontal">
<Rectangle Name="rec" RadiusX="2" RadiusY="2" Height="10" Width="10" />
<Label Name="lab" Content="{Binding ElementName=MyControl, Path=GraphName}" />
</StackPanel>
</CheckBox>
</StackPanel>
</UserControl>