我有一个自定义UserControl,我想将自定义属性附加到一些包含的UI元素。
我试图像这样实现它,但VS不接受我的XAML代码。 它说MyProp不可用或无法访问。
<UserControl
x:Class="mynamespace.MyDataSourceSelector"
xmlns:local="clr-namespace:mynamespace"
... >
<TabControl>
<TabItem Header="Tab1" local:MyDataSourceSelector.MyProp="something1"/>
<TabItem Header="Tab2" local:MyDataSourceSelector.MyProp="something2"/>
</TabControl>
<UserControl>
我的自定义UserControl类看起来像这样:
public partial class MyDataSourceSelector: UserControl
{
...
public string MyProp
{
get { return (string)GetValue(MyPropProperty); }
set { SetValue(MyPropProperty, value); }
}
public static readonly DependencyProperty MyPropProperty
= DependencyProperty.Register(
"MyProp",
typeof(string),
typeof(MyDataSourceSelector),
new PropertyMetadata(null)
);
}
我想为每个标签绑定一个值,然后在需要时读出活动标签的MyProp值。
我该怎么做?
答案 0 :(得分:0)
public static class TabItemExtensions
{
public static void SetMyProp(TabItem element, string value)
{
element.SetValue(MyPropProperty, value);
}
public static string GetMyProp(TabItem element)
{
return (string)element.GetValue(MyPropProperty);
}
public static readonly DependencyProperty MyPropProperty
= DependencyProperty.RegisterAttached(
"MyProp",
typeof(string),
typeof(TabItemExtensions),
new PropertyMetadata(null)
);
}
并像
一样使用它<TabItem Header="Tab1" local:TabItemExtensions.MyProp="something1"/>