从用户控制对话框返回值

时间:2017-06-12 18:31:44

标签: c# wpf mvvm

我正在尝试实现一个对话框来询问用户输入。我创建了一个usercontrol并将数据上下文绑定到ViewModel。我要求用户从列表中选择一个项目。我想将该选择传递回主程序。

try
{
    var ins = from Instrument in InstrumentList where Instrument.Comport == result.Comport select Instrument;
    result.OperatorName = ins.FirstOrDefault().OperatorName;
    result.OperatorID = ins.FirstOrDefault().OperatorID;
}
catch (Exception)
{
    //Open a control to prompt for instrument.
    Window window = new Window
    {
        Title = "Associate Com Port",
        Content = new MyDialogView(),
        SizeToContent = SizeToContent.WidthAndHeight,
        ResizeMode = ResizeMode.NoResize
    };
    window.ShowDialog();
    //var inst= ValueFromDialogBox
    //WriteInstrumentToConfigFile(inst);
    //Set proper Instrument/Comport pair
    GetAdditionalData(result);
}

所以我需要的是ValueFromDialogBox。我不介意能够获得多个价值。如果我可以传回一个物体,那么我可以做任何我想做的事情。

这是对话框的XAML(MyDialogView)

<UserControl.DataContext>
    <vm:MyDialogViewModel/>
</UserControl.DataContext>    

<UserControl.Resources>
    <ResourceDictionary Source="./MainWindowResources.xaml" />
</UserControl.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>

    <TextBlock Grid.Column="0"
               Grid.ColumnSpan="2"
               Grid.Row="0"
               Style="{StaticResource textStyle}" HorizontalAlignment="Center"
               Background="AliceBlue">
        <Run Text="What instrument are you using?" />
    </TextBlock>

    <TextBlock Grid.Column="0"
                Grid.Row="1"
                Style="{StaticResource textStyle}" 
               VerticalAlignment="Center"
               Background="AliceBlue">
        <Run Text="Select the Instrument number from the list."/>
    </TextBlock>

    <ListBox Grid.Column="1"
             Grid.Row="1"
             SelectedItem="{Binding InstrumentSelected}"
             ItemsSource="{Binding ListOfInstruments}"/>
    </Grid>

这是视图模型(MyDialogViewModel)

    public class MyDialogViewModel : ViewModelBase
{
    #region Fields
    string prompt;
    string comResponse;
    string comport;
    private string selectedInstrument;
    private ObservableCollection<string> listOfInstruments;

    #endregion

    #region Properties

    public string Prompt 
    {
        get { return prompt; }
        set 
        { 
            prompt = value;
            RaisePropertyChanged();

        }
    }

    public string ComResponse
    {
        get { return comResponse; }
        set 
        { 
            comResponse = value;
            RaisePropertyChanged();

        }
    }

    public string ComPort
    {
        get { return comport; }
        set 
        { 
            comport = value;
            RaisePropertyChanged();
        }
    }

    public string InstrumentSelected
    {
        get { return selectedInstrument; }

        set
        {
            if (value == selectedInstrument)
                return;
            selectedInstrument = value;

            base.RaisePropertyChanged();
        }
    }

    public ObservableCollection<string> ListOfInstruments
    {
        get { return listOfInstruments; }
        set
        {
            listOfInstruments = value;
            RaisePropertyChanged();

        }
    }
    #endregion

    #region Commands


    #endregion

    #region Methods



    #endregion

    #region Constructors

    public MyDialogViewModel()
    {
        listOfInstruments = new ObservableCollection<string>{
            "Instrument 1", "Instrument 2", "Instrument 3", "Instrument 4"
        };
    }

    public MyDialogViewModel(ref MainWindowViewModel mwvm)
    {
        listOfInstruments = new ObservableCollection<string>{
            "Instrument 1", "Instrument 2", "Instrument 3", "Instrument 4"
        };
    }
    #endregion
}

1 个答案:

答案 0 :(得分:1)

//Open a control to prompt for instrument.
Window window = new Window
{
    Title = "Associate Com Port",
    Content = new MyDialogView(),
    SizeToContent = SizeToContent.WidthAndHeight,
    ResizeMode = ResizeMode.NoResize
};
window.ShowDialog();

//  The view is the window content.
var view = (MyDialogView)window.Content;

//  The view XAML created an instance of MyDialogViewModel and assigned it to 
//  the view's DataContext.
MyDialogViewModel dlgVM = (MyDialogViewModel)view.DataContext;

//  Now you've got the viewmodel that was used in the dialog, with all its 
//  properties intact. 
MessageBox.Show($"Instrument selected was {dlgVM.InstrumentSelected}");

在这种情况下如何关闭窗口:

UserControl XAML:

<StackPanel 
    Orientation="Horizontal"
    >
    <Button
        Content="_OK"
        Click="OKButton_Click"
        />
    <Button
        Content="_Cancel"
        IsCancel="True"
        />
</StackPanel>

用户控件中的代码:

private void OKButton_Click(object sender, RoutedEventArgs e)
{
    Window.GetWindow(sender as DependencyObject).DialogResult = true;
}

如果您只是在其上设置IsCancel="True",则取消按钮有效。在这种情况下,ShowDialog()将返回false。在您明确设置DialogResult的情况下,ShowDialog()会返回您分配给DialogResult的bool值,除非它nullDialogResult = null无法关闭窗口。