从视图中绑定模型wpf c#

时间:2016-10-06 18:29:43

标签: c# wpf model viewmodel model-binding

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

我的ViewModel:

public class ViewModelProcessamentoArquivo : ViewModelBase
{
private PesquisaConfiguracao pesquisaConfiguracao;

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

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

我的DTO /模型

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; }
    }

我的观点就是这样。

<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" />

...

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

1 个答案:

答案 0 :(得分:0)

第一个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");
        }
    }

在属性设置器中放置一个BreakPoint,当你更改视图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"
        };
    }