求助使用 DependecyProperty 问题

zjj1211 2012-02-09 12:40:17
我创建一个wpf user control project

public partial class UserControl1 : UserControl
{
public static DependencyProperty ISProperty = DependencyProperty.Register("IS",
typeof(string), typeof(UserControl1), new PropertyMetadata(""));
[Category("Common Properties")]
public string IS
{
get { return (string)GetValue(ISProperty); }
set { SetValue(ISProperty, value); }
}
public UserControl1()
{
InitializeComponent();
MessageBox.Show(IS);
}
}

编译之后,作为一个控件拖到一个wpf项目中。

<Grid>
<my:UserControl1 HorizontalAlignment="Left" Name="userControl11" IS="test" />
</Grid>

然后给UserControl1的IS属性赋值 “test” 然后运行 wpf项目 MessageBox.Show弹出的是默认值而不是设置的本地值,
why?
...全文
75 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
manupstairs 2012-02-09
  • 打赏
  • 举报
回复
这是因为在走完构造函数以后,,才走到属性IS的set方法。
但是这不影响你使用本地值IS,只是你在构造函数中访问不到。
你只要加上this.DataContext = this;这句。你就可以再XAML中绑定IS属性了,比如


<UserControl x:Class="ButtonControlLibrary.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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">

<Button Content="{Binding IS}" Height="300" Width="300"></Button>
</UserControl>



public partial class MyUserControl : UserControl
{
public static DependencyProperty ISProperty = DependencyProperty.Register("IS",
typeof(string), typeof(MyUserControl), new PropertyMetadata(""));
[Category("Common Properties")]
public string IS
{
get { return (string)GetValue(ISProperty); }
set { SetValue(ISProperty, value); }
}
public MyUserControl()
{
InitializeComponent();
this.DataContext = this;

}
}

8,756

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧