将依赖项属性添加到文本框

时间:2012-07-13 06:39:26

标签: silverlight xaml mvvm dependency-properties

如何将依赖项属性添加到文本框,并将依赖项属性绑定到silver light中的Boolean属性。我的布尔属性在我的视图模型中。

ImageSearchIsFocused是允许我将焦点设置在文本框上的属性。

<TextBox  Text="{Binding ImgSearch, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">   
    <i:Interaction.Behaviors>
        <common:FocusBehavior HasInitialFocus="True" IsFocused="{Binding ImageSearchIsFocused, Mode=TwoWay}" ></common:FocusBehavior>
    </i:Interaction.Behaviors>
</TextBox>

ImageIsFocused Property

bool _ImageSearchIsFocused;
public bool ImageSearchIsFocused
{
    get { return _ImageSearchIsFocused; }
    set
    { 
        _ImageSearchIsFocused = value;
        NotifyPropertyChanged("ImageSearchIsFocused");
    }
}

1 个答案:

答案 0 :(得分:0)

如果要添加依赖项属性,则将使子类成为TextBox,并将依赖项属性添加到子类中。然后你可以将它绑定到你喜欢的任何东西:

public class MyTextBox : TextBox
{ 

    public static readonly DependencyProperty MyBooleanValueProperty = DependencyProperty.Register(
        "MyBooleanValue", typeof(bool), typeof(MyTextBox),
        new PropertyMetadata(new PropertyChangedCallback(MyBooleanValueChanged)));
    public bool MyBooleanValue
    {
        get { return (bool)GetValue(MyBooleanValueProperty); }
        set { SetValue(MyBooleanValueProperty, value); }
    }

    private static void MyBooleanValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var propValue = (bool)e.NewValue;
        var control = d as MyTextBox;

        // do something useful
    }

}