从视图 wpf c# 绑定模型

Binding model from a view wpf c#

我正在尝试构建一个 DTO 来存储软件配置,但我卡住了,因为我的视图没有将数据发送到我的 ViewModel 和我的 DTO。 我需要将 2 个文本框和 3 个组合框传输到我的 DTO,但使用此代码时值始终为空。

我的视图模型:

public class ViewModelProcessamentoArquivo : ViewModelBase
{
private PesquisaConfiguracao pesquisaConfiguracao;

public PesquisaConfiguracao PesquisaConfiguracao
        {
            get { return pesquisaConfiguracao; }
            set
            {
                pesquisaConfiguracao = value;

                base.OnPropertyChanged("PesquisaConfiguracao");
            }
        }
}

我的DTO/Model

public class PesquisaConfiguracao
    {
        public string ArquivoOrigem { get; set; }
        public string ArquivoDestino { get; set; }
        public string TipoPesquisa { get; set; }
        public string PesquisaVeicular { get; set; }
        public string PesquisaCrediticia { get; set; }
    }

而我的View是这样的

<TextBox Name="txtBuscarArquivoOrigem" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Height="30" Margin="10, 0" Text="{Binding PesquisaConfiguracao.ArquivoOrigem}" />

<TextBox  x:Name="txtBuscarArquivoDestino" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="3" Height="30" Margin="10, 0" Text="{Binding PesquisaConfiguracao.ArquivoDestino}" IsEnabled="false" />

...

你们知道为什么会这样吗?我在我的其他项目中使用过类似的东西并且工作得很好。另外,如果您有任何其他可能的方法来解决此问题,请发表评论!

首先 UpdateSourceTrigger PropertyChanged,这样目标(视图)将在每次更改时更新您的源对象:

   <TextBox Name="txtBuscarArquivoOrigem"  Height="30" Text="{Binding PesquisaConfiguracao.ArquivoOrigem, UpdateSourceTrigger=PropertyChanged}" />

然后在源对象的属性上实现 INotifyPropertyChange 接口,以便在值更改时更新视图:

  private string _arquivoOrigem;

    public string ArquivoOrigem
    {
        get
        {
            return _arquivoOrigem;
        }
        set
        {
            _arquivoOrigem = value;
            OnPropertyChanged("ArquivoOrigem");
        }
    }

在 属性 setter 中放置一个断点,当您更改视图 TextBox 中的值时它会在那里中断。

如果它对您不起作用,可能是忘记将您的 DataContext 设置为您的 ViewModel:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" 
    DataContext="{StaticResource MainViewModel}">

或者没有初始化你的源对象:

    public MainViewModel()
    {
        pesquisaConfiguracao = new PesquisaConfiguracao
        {
            ArquivoDestino = "aaa",
            ArquivoOrigem = "bbb",
            PesquisaCrediticia = "ccc",
            PesquisaVeicular = "dddd",
            TipoPesquisa = "eee"
        };
    }