Reputation: 562
I have a user control defined as follows:
<UserControl ...
......
x:name="StartPage">
<ToggleButton
x:Name="FullScreenToggle"
Content="{Binding ElementName=StartPage,Path=FullScreenState,Mode=OneWay}" />
</UserControl>
in the code behind:
public String FullScreenState
{
get;
set;
}
However for some reason the ToggleButton's Content property doesn't pick up the property. Any ideas?
Upvotes: 2
Views: 1127
Reputation: 93561
Your binding is perfectly valid, but you need to use an updatable property or the view will not be notified of the property changing.
Basically it needs to call PropertyChanged with the details of the changed property:
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"));
}
}
}
}
This means your control has to implement INotifyPropertyChanged:
public partial class SilverlightControl1 : UserControl, INotifyPropertyChanged
and provide the event handler:
public event PropertyChangedEventHandler PropertyChanged;
*As mentioned by tam, you can also use a dependency property if you want to extend your control for use in other controls. Horses for courses :)
Upvotes: 3
Reputation: 1583
you can also define your property as a dependency property, this would give you the flexibility to be able to bind to it later on in a bigger control
ex:
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));
Upvotes: 0
Reputation: 2935
You will have to set the DataContext of the UserControl:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
I believe you'll also have to remove the "ElementName" property from the binding statement. Then, you should should be able to bind to properties in the code behind.
Upvotes: 0