我一直在尝试使用dependencyproperty 创建一个简单的用户控件并将其绑定,但它似乎不起作用,不知道为什么。我将直接深入代码,请忽略控件没有意义的事实,这只是为了说明目的(如果重要的话,用 WP8 编写)。
我的简单用户控件,它基本上是一条带有属性的线来关闭或打开它。
<Grid x:Name="LayoutRoot" Background="Transparent"> <Line Height="105" Width="105" X2="100" Y2="100" Visibility="{Binding LineVisible}" Stroke="#FFFC1515" StrokeThickness="5"/> </Grid> public partial class SimpleUserControl : UserControl { public SimpleUserControl() { InitializeComponent(); DataContext = this; } public static readonly DependencyProperty LineVisibleProperty = DependencyProperty.Register("LineVisible", typeof(bool), typeof(SimpleUserControl), new PropertyMetadata(new PropertyChangedCallback(OnLineVisibleChanged))); public bool LineVisible { get { return (bool)GetValue(LineVisibleProperty); } set { SetValue(LineVisibleProperty, value); } } private static void OnLineVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { bool newvalue = (bool)e.NewValue; Visibility vis = newvalue ? Visibility.Visible : Visibility.Collapsed; (d as SimpleUserControl).Visibility = vis; } }
测试应用
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <uc:SimpleUserControl LineVisible="{Binding class1.Vis}"/> </Grid> public partial class MainPage : PhoneApplicationPage { public Class1 class1 { get; set; } public MainPage() { InitializeComponent(); DataContext = this; } private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e) { class1 = new Class1() { Vis = false }; } }
绑定的 class1
public class Class1 : INotifyPropertyChanged { private bool _vis; public bool Vis { get { return _vis; } set { _vis = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Vis")); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } }
但是,如果它像下面那样明确设置,它似乎不起作用。
<uc:SimpleUserControl LineVisible="False"/>
我确定这很简单,但我没有看到它。谢谢你的帮助。