1

I'd like to have a simple dialog box with text field. For now I have:

ViewModel:

   public class MyViewModel
   {
       public string AA { get; set; }
   }

View:

public partial class MyView : Window
{

    public MyView(MyViewModel context)
    {
        InitializeComponent();
        this.DataContext = context;
    }

    public string BB {get; set; }
 }

 <Window 
        ...>
      <Grid>

            <Label>name:</Label>
            <TextBox Width="110">
                <TextBox.Text>
                    <Binding Path="AA"/>
                </TextBox.Text>
            </TextBox>
            ...
       </Grid >
 </Window>

In order to open it and get the value I call:

   MyViewModel model = new MyViewModel();
   MyView dialog = new MyView(model);
   dialog.ShowDialog();

Now I'm able to take the provided TextBox value from the MyViewModel AA property.

Is it possible to store the provided value in the MyView BB property (and so remove the MyViewModel)? I tried to change the xaml configuration but no mater what I put there the BB property is always null.

The only reason I ask is that my dialog will do nothing more than collect this one single value and I'd like to keep it as thin as possible.

orwe
  • 233
  • 1
  • 3
  • 10
  • You should wrap that [dialog in a using block](https://msdn.microsoft.com/en-us/library/c7ykbedk.aspx) – phadaphunk Jan 22 '15 at 16:57
  • @phadaphunk, As `MyView` is a `Window` from WPF, it has no `Dispose` method. Calling `ShowDialog` should be enough for `Close` to get called and clean up. – chris Jan 22 '15 at 17:07
  • You mean the older winforms way of returning a value from a dialog, like [this](http://stackoverflow.com/a/5233526/302677)? – Rachel Jan 22 '15 at 19:41

3 Answers3

1
 <Window x:Name="root"
        ...>
      <Grid>

            <Label>name:</Label>
            <TextBox Width="110" Text="{Binding BB, ElementName=root} />
            ...
       </Grid >
 </Window>

should be all you need to do.

1

You can also simply replace

    this.DataContext = context;

by

    this.DataContext = this;

and i would put it before the InitializeComponent call.

But if you want to store the value from textbox to BB, then you also need to set the mode:

    <TextBox Text="{Binding BB, Mode=TwoWay}"/>

And don't forget to implement INotifyPropertyChanged in your MyView class.

Rob van Daal
  • 298
  • 1
  • 9
1

you could take the aprroach i use: Good or bad practice for Dialogs in wpf with MVVM?

here you call a dailogservice like

var result = this.uiDialogService.ShowDialog("Dialogwindow title goes here", dialogwindowVM);

... do anything with the dialog result...

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74