【问题标题】:WPF user control without view model没有视图模型的 WPF 用户控件
【发布时间】:2020-10-24 17:30:19
【问题描述】:

我试图在 WPF 中创建一个用户控件,它是一个简单的视图,没有视图模型。 我里面有一个标签和一个文本框。

ControlTextBox.xaml:

 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Name="LabelColumn"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label Grid.Column="0" Name="LabelControl"></Label>
    <TextBox Grid.Column="1"
             Name="TextBox"
             Width="Auto"
             HorizontalAlignment="Stretch"
             Height="22"></TextBox>
</Grid>

ControlTextBox.xaml.cs:

public partial class ControlTextBox : UserControl
{
    public ControlTextBox ()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(ControlTextBox),
            new PropertyMetadata(default(string), new PropertyChangedCallback(OnTextChanged)));
    
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

     private static void OnTextChanged(DependencyObject sender,
       DependencyPropertyChangedEventArgs args)
    {
        ControlTextBox controlTextBox = sender as ControlTextBox;
        controlTextBox.UpdateText(args);
    }
 
    private void UpdateText(DependencyPropertyChangedEventArgs args)
    {
        TextBox.Text = (string)args.NewValue;
    }
}

控件的使用位置:

<controls:ControlTextBox Text="{Binding PersonModel.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>

但是这样,在我使用控件的地方,绑定是以单一方式完成的。如果绑定的属性发生更改,我可以在文本框中看到它。 但是如果我在 textBox 中写一些新的东西,绑定的属性不会改变。

我应该怎么做才能从 textBox 更改为绑定属性?

【问题讨论】:

    标签: wpf binding dependency-properties


    【解决方案1】:

    在 ControlTextBox.xaml 中使用 RelativeSource 绑定:

    <TextBox ...
        Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" />
    

    并删除 PropertyChangedCallback:

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(nameof(Text), typeof(string), typeof(ControlTextBox));
    
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    

    【讨论】:

    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 2010-11-06
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多