开发者

XAML binding silverlight

开发者 https://www.devze.com 2023-03-13 07:51 出处:网络
开发者_如何学JAVAI have a user control defined as follows: <UserControl ... ...... x:name=\"StartPage\">
开发者_如何学JAVA

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?


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 :)


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.


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号