如何在TextBox与WPF中的MVVM绑定时设置TextBox.Text值

时间:2017-08-10 07:13:32

标签: wpf xaml

我正在使用WPF表单,我想知道如何通过TextBox与MVVM绑定来设置cv::cvtColor值。 例如:TextBox.Text我想将此值设置为文本框,将我的文本框设置为

TextBox.Text = "Hello";

我的WPF窗口窗体类:

下一个我的Xaml:

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        txtCityName.Text = "Hello Vaibhav";
        this.DataContext = new MyTesting();

    }
}

下一个我的模特:

 <Grid>
    <TextBox Name="txtCityName" Grid.Row="3" Grid.Column="1"   Text="{Binding CityName, UpdateSourceTrigger=PropertyChanged}" Height="40" Width="200"/>
</Grid>

但是分配给TextBox的NULL。如何解决这个问题

2 个答案:

答案 0 :(得分:0)

txtCityName.Text = "YourCity"不是MVVM。

您应该设置CityName源属性,而不是设置Text控件的TextBox属性。

<TextBox Name="txtCityName" Grid.Row="3" Grid.Column="1" Text="{Binding CityName}">
this.DataContext = new AddressModel();

AddressModel obj = this.DataContext as AddressModel;
obj.CityName = "..."; //<--this will update the data-bound TextBox

答案 1 :(得分:0)

我觉得对于遵循 MVVM 来说,接受的答案实际上并不正确。我在 WPF 中尝试使用 Windows.Forms.OpenFileDialog() 时遇到了这个问题。虽然使用 Windows.Forms.OpenFileDialog 从技术上讲不是 MVVM,但如果您将对话框用作“仅查看”机制来查找文件名,则使用此处找到的反射 https://stackoverflow.com/a/11122289/15464066。这将在允许使用 OpenFileDialog() 的同时实现 MVVM。