我一直在尝试使用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"/>
我确信这很简单,但我没有看到它。 谢谢你的帮助。
答案 0 :(得分:1)
问题是我在UserControl中设置了DataContext = this,当在testapp中绑定到Vis时,它会覆盖并在UserControl中搜索Vis(当然在那里不存在)。我确实在调试输出窗口中看到了绑定错误,这证实了这一点。解决方案是将UserControl的LayoutRoot设置为此,如前面发布的链接中所述。
答案 1 :(得分:0)