C# WPF MVVM如何使用ShowDialog()上的绑定预填充文本框?

C# WPF MVVM如何使用ShowDialog()上的绑定预填充文本框?,c#,wpf,mvvm,dialog,C#,Wpf,Mvvm,Dialog,我有一个用ShowDialog()显示的窗体窗口,文本框绑定到视图模型中的属性。 我按如下方式打开对话框(简化版): 我在表单中设置的属性用作过滤器参数,我将其存储在一个静态类中以供以后使用 我想做的是让文本框自动填充这个静态类中存储的当前值 我的文本框绑定属性如下所示: private string _product; public string product { get { return _product; } set

我有一个用
ShowDialog()
显示的窗体窗口,文本框绑定到视图模型中的属性。 我按如下方式打开对话框(简化版):

我在表单中设置的属性用作过滤器参数,我将其存储在一个静态类中以供以后使用

我想做的是让文本框自动填充这个静态类中存储的当前值

我的文本框绑定属性如下所示:

    private string _product;
    public string product
    {
        get { return _product; }
        set
        {
            if (_product == value)
                return;
            _product = value;
            Helper.product = value;
            if (value != "")
                chkProduct = true;
            OnPropertyChanged();
        }
    }
(我认为在验证时重新分配可能会更好,但这是另一个问题…) 我这里的问题是,如果我设置了一个值(即在构造函数中),则会设置该值,但在调用
ShowDialog()
时,该值会重置为“”

还尝试在实例化VM后调用方法,但如上所述,此重置在显示窗口时发生(调用
ShowDialog()

这个表单生成了一个自定义对象,我在VM
对话框result
中恢复,所以我不选择
wnd.Show()
,然后设置为存储值(我想是吧?)

谢谢你的帮助

编辑视图非常简单,只有几个标签和文本框双向绑定到虚拟机

<Window x:Class="LicenseManager.View.FilterWindowView"
    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"
    xmlns:local="clr-namespace:LicenseManager.View"
    mc:Ignorable="d"
    Title="FilterWindowView" Height="306.412" Width="284.216">
<Grid>
    <CheckBox Content="Product" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" IsChecked="{Binding chkProduct}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,8,0,0" TextWrapping="Wrap" Text="{Binding product, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <CheckBox Content="Client" HorizontalAlignment="Left" Margin="10,38,0,0" VerticalAlignment="Top" IsChecked="{Binding chkClient}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,36,0,0" TextWrapping="Wrap" Text="{Binding client, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <CheckBox Content="Date After" HorizontalAlignment="Left" Margin="10,66,0,0" VerticalAlignment="Top" IsChecked="{Binding chkDateAfter}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,64,0,0" TextWrapping="Wrap" Text="{Binding dateAfter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <CheckBox Content="Date Before" HorizontalAlignment="Left" Margin="10,94,0,0" VerticalAlignment="Top" IsChecked="{Binding chkDateBefore}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,92,0,0" TextWrapping="Wrap" Text="{Binding dateBefore, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <CheckBox Content="Sbs__no" HorizontalAlignment="Left" Margin="10,122,0,0" VerticalAlignment="Top" IsChecked="{Binding chkSbsNo}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,120,0,0" TextWrapping="Wrap" Text="{Binding sbsNo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <CheckBox Content="Store__no" HorizontalAlignment="Left" Margin="10,150,0,0" VerticalAlignment="Top" IsChecked="{Binding chkStoreNo}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,148,0,0" TextWrapping="Wrap" Text="{Binding storeNo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <CheckBox Content="Workstation__no" HorizontalAlignment="Left" Margin="10,178,0,0" VerticalAlignment="Top" IsChecked="{Binding chkWorkstationNo}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,176,0,0" TextWrapping="Wrap" Text="{Binding workstationNo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <CheckBox Content="Comment" HorizontalAlignment="Left" Margin="10,206,0,0" VerticalAlignment="Top" IsChecked="{Binding chkWorkstationNo}"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="137,204,0,0" TextWrapping="Wrap" Text="{Binding comment, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <Button Content="Apply" Command="{Binding apply}" HorizontalAlignment="Left" Margin="10,236,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>

编辑视图模型类 Helper是我的静态类

    class FilterWindowViewModel : INotifyPropertyChanged
        {
            #region Attributes
            public Window wnd; // For dialog closer
            public List<LicenseRecordModel> list;
            public List<LicenseRecordModel> dialogResult;
            public event PropertyChangedEventHandler PropertyChanged;

            string tmpProduct;
            string tmpClient;
            string tmpDateAfter;
            string tmpDateBefore;
            string tmpSbsNo;
            string tmpStoreNo;
            string tmpWorkstationNo;
            string tmpComment;
            #endregion

            #region Properties
            //Properties and commands
        private string _comment;
        public string comment
        {
            get { return _comment; }
            set
            {
                if (_comment == value)
                    return;
                _comment = value;
                Helper.comment = value;
                if (value != "")
                    chkComment = true;
                OnPropertyChanged();
            }
        }


//...
        private DelegateCommand _apply;
        public DelegateCommand apply
        {
            get
            {
                return _apply ?? (_apply = new DelegateCommand(o => Apply(), o => true));
            }
        }
            #endregion

            #region Init
            public FilterWindowViewModel(IEnumerable<LicenseRecordModel> source)
            {
                tmpProduct = Helper.product;
                tmpClient = Helper.client;
                tmpDateAfter = Helper.dateAfter;
                tmpDateBefore= Helper.dateBefore;
                tmpSbsNo = Helper.sbsNo;
                tmpStoreNo = Helper.storeNo;
                tmpWorkstationNo = Helper.workstationNo;
                tmpComment = Helper.comment;
                list = new List<LicenseRecordModel>(source);
            }

            public void RestoreCurrentFilters()
            {
                product = tmpProduct;
                client = tmpClient;
                dateAfter = tmpDateAfter;
                dateBefore = tmpDateBefore;
                sbsNo = tmpSbsNo;
                storeNo = tmpStoreNo;
                workstationNo = tmpWorkstationNo;
                comment = tmpComment;
            }

            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChangedEventHandler handler = PropertyChanged;

                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
            #endregion

            private bool Accept(LicenseRecordModel lic)
            {
                var tmp = list;
                tmp = list.Where(x => 
                chkProduct ? x.Product.Contains(product) : true &&
                chkClient ? x.Client.Contains(client) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true
                ).ToList();
                return false;
            }

            #region Commands
            public void Apply()
            {
                var tmp = new List<LicenseRecordModel>(list);
                dialogResult = new List<LicenseRecordModel>(list);
                string message = "";
                if (chkProduct)
                {
                    dialogResult =tmp.Where(x => x.Product.Contains(product.ToUpper())).ToList();
                    tmp = dialogResult;
                }
                if (chkClient)
                {
                    dialogResult = tmp.Where(x => x.Client.Contains(client.ToUpper())).ToList();
                    tmp = dialogResult;
                }
                if (chkDateAfter)
                {
                    DateTime after;
                    if (chkDateBefore)
                    {
                        DateTime before;
                        if (DateTime.TryParse(dateAfter, out after))
                        {
                            if (DateTime.TryParse(dateBefore, out before))
                            {
                                dialogResult = tmp.Where(x => DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) <= after && DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) >= before).ToList(); ;
                                tmp = dialogResult;
                            }
                            else message += "'Date Before' is not a valid date (yyyy-mm-dd)";
                        }
                        else message += "'Date After' is not a valid date (yyyy-mm-dd)";
                    }
                    else if (DateTime.TryParse(dateAfter, out after))
                    {
                        dialogResult = tmp.Where(x => DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) >= after).ToList();
                        tmp = dialogResult;
                    }
                    else message += "'Date After' is not a valid date (yyyy-mm-dd)";
                }
                if (chkDateBefore)
                {
                    DateTime before;
                    if (DateTime.TryParse(dateBefore, out before))
                    {
                        dialogResult = tmp.Where(x => DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) <= before).ToList();
                        tmp = dialogResult;
                    }
                    else message += "'Date After' is not a valid date (yyyy-mm-dd)";
                }
                if (chkSbsNo)
                {
                    dialogResult = tmp.Where(x => x.SbsNo.Contains(sbsNo)).ToList();
                    tmp = dialogResult;
                }
                if (chkStoreNo)
                {
                    dialogResult = tmp.Where(x => x.StoreNo.Contains(storeNo)).ToList();
                    tmp = dialogResult;
                }
                if (chkWorkstationNo)
                {
                    dialogResult = tmp.Where(x => x.WorkstationNo.Contains(workstationNo)).ToList();
                    tmp = dialogResult;
                }
                if (chkComment)
                {
                    dialogResult = tmp.Where(x => x.Comment.ToUpper().Contains(comment.ToUpper())).ToList();
                    tmp = dialogResult;
                }
                if (message != "")
                {
                    MessageBox.Show(message);
                }
                else
                {
                    DialogCloser.SetDialogResult(wnd, true);
                }
            }
            #endregion
        }
class FilterWindowViewModel:INotifyPropertyChanged
{
#区域属性
公共窗口wnd;//用于关闭对话框
公开名单;
公开列表结果;
公共事件属性更改事件处理程序属性更改;
字符串tmpProduct;
字符串tmpClient;
字符串tmpDateAfter;
字符串tmpDateBefore;
字符串tmpSbsNo;
字符串tmpStoreNo;
字符串tmpWorkstationNo;
字符串TMP命令;
#端区
#区域属性
//属性和命令
私有字符串\u注释;
公共字符串注释
{
获取{return\u comment;}
设置
{
如果(_comment==值)
返回;
_评论=价值;
Helper.comment=值;
如果(值!=“”)
chkComment=true;
OnPropertyChanged();
}
}
//...
专用授权命令(u apply);;
公共委托人命令应用
{
得到
{
返回_apply??(_apply=newdelegateCommand(o=>apply(),o=>true));
}
}
#端区
#区域初始化
公共筛选器Windows视图模型(IEnumerable源)
{
tmpProduct=Helper.product;
tmpClient=Helper.client;
tmpDateAfter=Helper.dateAfter;
tmpDateBefore=Helper.dateBefore;
tmpSbsNo=Helper.sbsNo;
tmpStoreNo=Helper.storeNo;
tmpWorkstationNo=Helper.workstationNo;
tmpComment=Helper.comment;
列表=新列表(源);
}
公共无效恢复筛选器()
{
产品=tmpProduct;
客户=TMP客户;
dateAfter=tmpDateAfter;
dateBefore=tmpDateBefore;
sbsNo=tmpSbsNo;
storeNo=tmpStoreNo;
工作站编号=TMP工作站编号;
评论=TMP评论;
}
受保护的OnPropertyChanged无效([CallerMemberName]字符串propertyName=null)
{
PropertyChangedEventHandler处理程序=PropertyChanged;
if(处理程序!=null)
{
处理程序(这是新的PropertyChangedEventArgs(propertyName));
}
}
#端区
private bool Accept(LicenseRecordModel lic)
{
var tmp=列表;
tmp=列表。其中(x=>
chkProduct?x.Product.Contains(产品):true&&
chkClient?x.Client.Contains(客户端):true&&
chkProduct?x.Product.Contains(产品):true&&
chkProduct?x.Product.Contains(产品):true&&
chkProduct?x.Product.Contains(产品):true&&
chkProduct?x.Product.Contains(产品):true&&
chkProduct?x.Product.Contains(产品):true
).ToList();
返回false;
}
#区域命令
公开无效申请()
{
var tmp=新列表(列表);
dialogResult=新列表(列表);
字符串消息=”;
if(chkProduct)
{
dialogResult=tmp.Where(x=>x.Product.Contains(Product.ToUpper()).ToList();
tmp=对话结果;
}
if(chkClient)
{
dialogResult=tmp.Where(x=>x.Client.Contains(Client.ToUpper()).ToList();
tmp=对话结果;
}
if(chkDateAfter)
{
日期时间之后;
if(chkDateBefore)
{
日期时间;
if(DateTime.TryParse(dateAfter,out after))
{
if(DateTime.TryParse(dateBefore,out before))
{
dialogResult=tmp.Where(x=>DateTime.ParseExact(x.CreationDate,“yyyy-MM-dd”,null)=before.ToList();
tmp=对话结果;
}
    class FilterWindowViewModel : INotifyPropertyChanged
        {
            #region Attributes
            public Window wnd; // For dialog closer
            public List<LicenseRecordModel> list;
            public List<LicenseRecordModel> dialogResult;
            public event PropertyChangedEventHandler PropertyChanged;

            string tmpProduct;
            string tmpClient;
            string tmpDateAfter;
            string tmpDateBefore;
            string tmpSbsNo;
            string tmpStoreNo;
            string tmpWorkstationNo;
            string tmpComment;
            #endregion

            #region Properties
            //Properties and commands
        private string _comment;
        public string comment
        {
            get { return _comment; }
            set
            {
                if (_comment == value)
                    return;
                _comment = value;
                Helper.comment = value;
                if (value != "")
                    chkComment = true;
                OnPropertyChanged();
            }
        }


//...
        private DelegateCommand _apply;
        public DelegateCommand apply
        {
            get
            {
                return _apply ?? (_apply = new DelegateCommand(o => Apply(), o => true));
            }
        }
            #endregion

            #region Init
            public FilterWindowViewModel(IEnumerable<LicenseRecordModel> source)
            {
                tmpProduct = Helper.product;
                tmpClient = Helper.client;
                tmpDateAfter = Helper.dateAfter;
                tmpDateBefore= Helper.dateBefore;
                tmpSbsNo = Helper.sbsNo;
                tmpStoreNo = Helper.storeNo;
                tmpWorkstationNo = Helper.workstationNo;
                tmpComment = Helper.comment;
                list = new List<LicenseRecordModel>(source);
            }

            public void RestoreCurrentFilters()
            {
                product = tmpProduct;
                client = tmpClient;
                dateAfter = tmpDateAfter;
                dateBefore = tmpDateBefore;
                sbsNo = tmpSbsNo;
                storeNo = tmpStoreNo;
                workstationNo = tmpWorkstationNo;
                comment = tmpComment;
            }

            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChangedEventHandler handler = PropertyChanged;

                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
            #endregion

            private bool Accept(LicenseRecordModel lic)
            {
                var tmp = list;
                tmp = list.Where(x => 
                chkProduct ? x.Product.Contains(product) : true &&
                chkClient ? x.Client.Contains(client) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true &&
                chkProduct ? x.Product.Contains(product) : true
                ).ToList();
                return false;
            }

            #region Commands
            public void Apply()
            {
                var tmp = new List<LicenseRecordModel>(list);
                dialogResult = new List<LicenseRecordModel>(list);
                string message = "";
                if (chkProduct)
                {
                    dialogResult =tmp.Where(x => x.Product.Contains(product.ToUpper())).ToList();
                    tmp = dialogResult;
                }
                if (chkClient)
                {
                    dialogResult = tmp.Where(x => x.Client.Contains(client.ToUpper())).ToList();
                    tmp = dialogResult;
                }
                if (chkDateAfter)
                {
                    DateTime after;
                    if (chkDateBefore)
                    {
                        DateTime before;
                        if (DateTime.TryParse(dateAfter, out after))
                        {
                            if (DateTime.TryParse(dateBefore, out before))
                            {
                                dialogResult = tmp.Where(x => DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) <= after && DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) >= before).ToList(); ;
                                tmp = dialogResult;
                            }
                            else message += "'Date Before' is not a valid date (yyyy-mm-dd)";
                        }
                        else message += "'Date After' is not a valid date (yyyy-mm-dd)";
                    }
                    else if (DateTime.TryParse(dateAfter, out after))
                    {
                        dialogResult = tmp.Where(x => DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) >= after).ToList();
                        tmp = dialogResult;
                    }
                    else message += "'Date After' is not a valid date (yyyy-mm-dd)";
                }
                if (chkDateBefore)
                {
                    DateTime before;
                    if (DateTime.TryParse(dateBefore, out before))
                    {
                        dialogResult = tmp.Where(x => DateTime.ParseExact(x.CreationDate, "yyyy-MM-dd", null) <= before).ToList();
                        tmp = dialogResult;
                    }
                    else message += "'Date After' is not a valid date (yyyy-mm-dd)";
                }
                if (chkSbsNo)
                {
                    dialogResult = tmp.Where(x => x.SbsNo.Contains(sbsNo)).ToList();
                    tmp = dialogResult;
                }
                if (chkStoreNo)
                {
                    dialogResult = tmp.Where(x => x.StoreNo.Contains(storeNo)).ToList();
                    tmp = dialogResult;
                }
                if (chkWorkstationNo)
                {
                    dialogResult = tmp.Where(x => x.WorkstationNo.Contains(workstationNo)).ToList();
                    tmp = dialogResult;
                }
                if (chkComment)
                {
                    dialogResult = tmp.Where(x => x.Comment.ToUpper().Contains(comment.ToUpper())).ToList();
                    tmp = dialogResult;
                }
                if (message != "")
                {
                    MessageBox.Show(message);
                }
                else
                {
                    DialogCloser.SetDialogResult(wnd, true);
                }
            }
            #endregion
        }
<TextBox Text="{Binding product, UpdateSourceTrigger=PropertyChanged}" />
public partial class MainWindow
{
  // Shared and reused view model instance
  private FilterWindowViewModel DialogViewModel{ get; set; }

  public MainWindow()
  { 
    this.DialogViewModel = new FilterWindowViewModel();
  }

  private void ShowDialog()
  {
    var dialog = new FilterWindowView() { DataContext = this.DialogViewModel };
    if (dialog.ShowDialog() ?? false)
    {
      //...
    }
  }
}
public class FilterWindowViewModel 
{
  private string _product;
  public string Product
  {
    get => _product; 
    set
    {
      if (_product == value)
        return;

      _product = value;

      this.chkProduct = !string.IsNullOrWhiteSpace(value);
      OnPropertyChanged();
    }
  }
}