我在WPF中创建了一个用户控件:
<UserControl
x:Class="BARCIndia.Mobile.Views.UserControls.SubCategoryUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BARCIndia.Mobile.Views.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<StackPanel Background="DarkCyan">
<TextBlock Name="txtName" FontSize="26"></TextBlock>
</StackPanel>
</Grid>
</UserControl>
后面的代码有一个名为&#34; ParamValue
&#34;它设置为我的用户控件TextBlock:txtName
public sealed partial class SubCategoryUserControl : UserControl
{
public string ParamValue
{
get { return (string)GetValue(ParamValueProperty); }
set { SetValue(ParamValueProperty, value); }
}
public static readonly DependencyProperty ParamValueProperty = DependencyProperty.Register
(
"ParamValue",
typeof(string),
typeof(SubCategoryUserControl),
new PropertyMetadata(string.Empty)
);
public SubCategoryUserControl()
{
this.InitializeComponent();
txtName.Text = this.ParamValue;
}
}
从xaml表单调用
<Grid >
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Myusercontrol:SubCategoryUserControl x:Name="tempUserControl" ParamValue="From Window" Grid.Row="0"/>
</Grid>
这里我传递参数 ParamValue =&#34;来自Window&#34; 当usercontrol加载的文本块显示为空时。
属性未更新其显示的emtry字符串,即在创建依赖属性时分配的默认值
public static readonly DependencyProperty ParamValueProperty = DependencyProperty.Register
(
"ParamValue",
typeof(string),
typeof(SubCategoryUserControl),
**new PropertyMetadata(string.Empty)**
);
我如何获得指定值?
答案 0 :(得分:0)
在您的情况下,它可能如下所示:
public sealed partial class SubCategoryUserControl : UserControl
{
public string ParamValue
{
get
{
return (string) GetValue(ParamValueProperty);
}
set
{
SetValue(ParamValueProperty, value);
}
}
public static readonly DependencyProperty ParamValueProperty = DependencyProperty.Register
(
"ParamValue",
typeof (string),
typeof (SubCategoryUserControl),
new PropertyMetadata(string.Empty)
);
public SubCategoryUserControl()
{
this.InitializeComponent();
}
}
和xaml:
<UserControl x:Class="BARCIndia.Mobile.Views.UserControls.SubCategoryUserControl"
x:Name="Root"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BARCIndia.Mobile.Views.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<StackPanel Background="DarkCyan">
<TextBlock Text="{Binding ParamValue, ElementName=Root}" FontSize="26" />
</StackPanel>
</Grid>
</UserControl>