问题描述
|
我有一个定义如下的用户控件:
<UserControl ...
......
x:name=\"StartPage\">
<ToggleButton
x:Name=\"FullScreenToggle\"
Content=\"{Binding ElementName=StartPage,Path=FullScreenState,Mode=OneWay}\" />
</UserControl>
在后面的代码中:
public String FullScreenState
{
get;
set;
}
但是,由于某些原因,ToggleButton \的Content属性不能选择该属性。
有任何想法吗?
解决方法
您的绑定是完全有效的,但是您需要使用可更新的属性,否则该属性更改不会通知视图。
基本上,它需要使用已更改属性的详细信息来调用PropertyChanged:
private string _fullScreenState;
public string FullScreenState
{
get { return _fullScreenState; }
set
{
if (_fullScreenState != value)
{
_fullScreenState = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this,new PropertyChangedEventArgs(\"FullScreenState\"));
}
}
}
}
这意味着您的控件必须实现INotifyPropertyChanged:
public partial class SilverlightControl1 : UserControl,INotifyPropertyChanged
并提供事件处理程序:
public event PropertyChangedEventHandler PropertyChanged;
*如tam所述,如果要扩展控件以在其他控件中使用,也可以使用依赖项属性。马匹:)
, 您将必须设置UserControl的DataContext:
DataContext=\"{Binding RelativeSource={RelativeSource Self}}\"
我相信您还必须从绑定语句中删除\“ ElementName \”属性。
然后,您应该应该能够绑定到后面代码中的属性。
, 您还可以将属性定义为依赖项属性,这将为您提供灵活性,以便以后可以在更大的控件中对其进行绑定
例如:
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty,value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation,styling,binding,etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register(\"MyProperty\",typeof(int),typeof(ownerclass),new UIPropertyMetadata(0));