logo
Tags down

shadow

MVVM Passing data to dialog View Model


By : user3850918
Date : October 18 2020, 11:12 AM
Hope that helps I would perhaps do it in the following way:
The command attached to the edit button starts edit dialog, creating a custom ViewModel (VM) for it. The command itself should be perhaps either in the list's VM or in the Model (not quite sure). Foobar edit dialog's VM gets a reference to the Foobar at its constructor. The foobar is cloned and the clone is edited. As soon as the user presses OK in the foobar edit dialog, the clone's values are written back to the original foobar in the VM (and the dialog is closed).
code :


Share : facebook icon twitter icon

Passing state of WPF ValidationRule to View Model in MVVM


By : Danny Cicorella
Date : March 29 2020, 07:55 AM
I wish this help you Nirvan
The simplest way to solve this particular issue is to use a numeric textbox, which prevents the user from entering an invalid value (you can either do this via a Third Party Vendor, or find an open source solution, such as a class derived from Textbox that suppresses non numeric input).
code :
// original field
private int _age;
int Age 
{
   get { return _age; }
   set { 
     _age = value; 
     RaisePropertyChanged("Age");
   }
}


private string _ageStr;
string AgeStr
{
   get { return _ageStr; }
   set { 
     _ageStr = value; 
     RaisePropertyChanged("AgeStr");
     if (!String.IsNullOrEmpty(AgeStr) && IsNumeric(AgeStr) )
         Age = intVal;
    }
} 

private bool IsNumeric(string numStr)
{
   int intVal;
   return int.TryParse(AgeStr, out intVal);
}

#region IDataErrorInfo Members

    public string this[string columnName]
    {
        get
        {

            if (columnName == "AgeStr" && !IsNumeric(AgeStr)
               return "Age must be numeric";
        }
    }

    #endregion

to show a dialog: what is the difference of use messageBox and create a view and a view model in MVVM pattern?


By : Alexis Rendon
Date : March 29 2020, 07:55 AM
I wish this helpful for you In my opinion, creating a ViewModel for a MessageBox is overkill. I'd create an interface for ViewModels with a ShowMessage event, and an attached behavior with an attached property that can bind to the ViewModel, register a listener for the ShowMessage event, and opens a MessageBox when the event is raised. The result of the message box could be passed through the EventArgs.
The difference here would be that you can encapsulate the interface and the attached behaviour in a reusable component, and that you need minimal code in the ViewModel to use it.

Passing window handle to view model in WPF with MVVM


By : CyberTechie
Date : March 29 2020, 07:55 AM
Any of those help Typically, your view model shouldn't know about the implementation details of your view (such as it's HWND). However, as your question indicates, the external library you are using requires you to initialize it, and you can only do that in one place. Assuming that your view model is the most appropriate place for it (it might even belong in the model), you can do something like the following.
This implementation provides the window handle to your view model as soon as all the pieces are available. Note that the view model implementation that you provided in your previous question requires the HWND in the view model's constructor. You're going to have to change your view model so that the initialization happens via an explicitly called method or property. In the code below, I assume that there is a method in your view model called OnWindowHandleAvailable. You could certainly call that method Initialize instead, or you could put a Handle property on your view model which you explicitly set.
code :
public partial class View
{
    public View()
    {
        InitializeComponent();
        this.Loaded += View_Loaded;
        this.DataContextChanged += View_DataContextChanged;
    }

    private void View_Loaded(object sender, RoutedEventArgs e)
    {
        GiveWindowHandleToViewModel();
    }

    private void View_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        GiveWindowHandleToViewModel();
    }

    private void GiveWindowHandleToViewModel()
    {
        // get view model
        var viewModel = this.DataContext as ViewModel;
        if (viewModel == null)
            return;

        // get window handle
        var windowHandle = this.GetWindowHandle();
        if (windowHandle == IntPtr.Zero)
            return;

        // signal view model
        viewModel.OnWindowHandleAvailable(windowHandle);
    }

    private IntPtr GetWindowHandle()
    {
        // get window
        var window = Window.GetWindow(this);
        if (window == null)
            return IntPtr.Zero;

        // get window handle
        return new WindowInteropHelper(window).Handle;
    }
}

Passing data to an existing view model in MVVM-C pattern on iOS


By : Abdulrhman Mohamed
Date : September 30 2020, 03:00 AM
will help you You need to add observer for that.. No need to pass data in view model.
Calling observer from anywhere is the best pattern for MVVM to pass data

How to pass the Confirmation box clicked 'Yes' to a separate view model? How to show dialog the MVVM way?


By : Alienson
Date : September 07 2020, 12:00 AM
To fix the issue you can do This is a working example. It shows the recommended way to display a dialog from the view model without violating the MVVM pattern by using an attached behavior. It is very flexible in terms of customization as it makes use of DataTemplate to design the content of a dialog which is an instance of Window.
Setting the DialogViewModel property of the ViewModel (see example) will trigger the display of the dialog. An implicit DataTemplate (recommended to be defined in the global ResourceDictionary of the App.xaml file) will define the content of the dialog. Each DataTemplate must target an implementation of DialogViewModel (DataTemplate.DataType).
code :
public class Dialog : DependencyObject
{
  #region DialogDataContext attached property

  public static readonly DependencyProperty DialogDataContextProperty = DependencyProperty.RegisterAttached(
    "DialogDataContext", typeof(DialogViewModel), typeof(Dialog), new PropertyMetadata(default(DialogViewModel), Dialog.OnDialogDataContextChanged));

  public static void SetDialogDataContext(DependencyObject attachingElement, DialogViewModel value) => attachingElement.SetValue(Dialog.DialogDataContextProperty, value);

  public static DialogViewModel GetDialogDataContext(DependencyObject attachingElement) => (DialogViewModel)attachingElement.GetValue(Dialog.DialogDataContextProperty);

  #endregion

  private static Dictionary<DialogViewModel, Window> ViewModelToDialogMap { get; }

  static Dialog()
  {
    Dialog.ViewModelToDialogMap = new Dictionary<DialogViewModel, Window>();
  }

  public static bool TryGetDialog(DialogViewModel viewModel, out Window dialog) => Dialog.ViewModelToDialogMap.TryGetValue(viewModel, out dialog);

  private static void OnDialogDataContextChanged(DependencyObject attachingElement, DependencyPropertyChangedEventArgs e)
  {
    if (e.NewValue is DialogViewModel newDialogViewModel && attachingElement is FrameworkElement frameworkElement)
    {
      if (frameworkElement.IsLoaded)
      {
        Dialog.Show(attachingElement, newDialogViewModel);
      }
      else
      {
        frameworkElement.Loaded += Dialog.ShowDialogOnAttachingElementLoaded;
      }
    }
  }

  private static void ShowDialogOnAttachingElementLoaded(object sender, RoutedEventArgs e)
  {
    if (sender is Window window
        && window.DataContext is DialogViewModel dialogViewModel)
    {
      window.ContentTemplate = window.TryFindResource(dialogViewModel.GetType()) as DataTemplate;
    }
  }

  private static void Show(DependencyObject attachingElement, DialogViewModel newDialogViewModel)
  {
    newDialogViewModel.InteractionCompleted += Dialog.CloseDialogOnInteractionCompleted;
    Window window = Dialog.Prepare(attachingElement, newDialogViewModel);
    window.Closed += Dialog.CleanUpOnDialogClosed;
    Dialog.ViewModelToDialogMap.Add(newDialogViewModel, window);
    window.Show();
  }

  private static Window Prepare(DependencyObject attachingElement, DialogViewModel newDialogViewModel)
  {
    var window = new Window
    {
      Icon = newDialogViewModel.TitleBarIcon,
      SizeToContent = SizeToContent.WidthAndHeight,
      WindowStartupLocation = WindowStartupLocation.CenterOwner,
      Topmost = true,
      Title = newDialogViewModel.Title,
      DataContext = newDialogViewModel,
      Content = newDialogViewModel,
      ContentTemplateSelector = Dialog.GetDataTemplateSelector(attachingElement),
      Style = Dialog.GetStyle(attachingElement)
    };

    if (attachingElement is Window parentWindow
        || Dialog.TryFindVisualParentElement(attachingElement, out parentWindow))
    {
      window.Owner = parentWindow;
    }
    return window;
  }

  private static bool TryFindVisualParentElement<TParent>(DependencyObject child, out TParent resultElement)
    where TParent : DependencyObject
  {
    resultElement = null;

    DependencyObject parentElement = VisualTreeHelper.GetParent(child);

    if (parentElement is TParent parent)
    {
      resultElement = parent;
      return true;
    }

    return Dialog.TryFindVisualParentElement(parentElement, out resultElement);
  }

  private static void CleanUpOnDialogClosed(object sender, EventArgs e)
  {
    var dialogViewModel = (sender as Window).DataContext as DialogViewModel;
    Dialog.ViewModelToDialogMap.Remove(dialogViewModel);
    dialogViewModel.InteractionCompleted -= Dialog.CloseDialogOnInteractionCompleted;
  }

  private static void CloseDialogOnInteractionCompleted(object sender, EventArgs e)
  {
    if (Dialog.ViewModelToDialogMap.TryGetValue(sender as DialogViewModel, out Window dialog))
    {
      dialog.Close();
    }
  }
}
public abstract class DialogViewModel : INotifyPropertyChanged
{
  protected DialogViewModel(string message, string title) : this(message, title, (dialogViewModel) => Task.CompletedTask)
  {
  }
  protected DialogViewModel(string message, string title, Func<DialogViewModel, Task> sendResponseCallbackAsync) : this(message, title, null, sendResponseCallbackAsync)
  {
  }

  protected DialogViewModel(string message, string title, ImageSource titleBarIcon, Func<DialogViewModel, Task> sendResponseCallbackAsync)
  {
    this.ResponseCallbackAsync = sendResponseCallbackAsync;
    this.Message = message;
    this.Title = title;
    this.TitleBarIcon = titleBarIcon;
  }

  protected virtual async void ExecuteResponseCallback(object result)
  {
    this.DialogResult = (DialogResult) result;
    await this.ResponseCallbackAsync.Invoke(this).ConfigureAwait(false);
    OnInteractionCompleted();
  }

  private string title;   
  public string Title
  {
    get => this.title;
    set 
    { 
      this.title = value; 
      OnPropertyChanged();
    }
  }


  private string message;   
  public string Message
  {
    get => this.message;
    set 
    { 
      this.message = value; 
      OnPropertyChanged();
    }
  }

  private ImageSource titleBarIcon;
  public ImageSource TitleBarIcon
  {
    get => this.titleBarIcon;
    set
    {
      this.titleBarIcon = value;
      OnPropertyChanged();
    }
  }

  public RelayCommand SendResponseCommand => new RelayCommand(ExecuteResponseCallback, (param) => true);

  private DialogResult dialogResult;   
  public DialogResult DialogResult
  {
    get => this.dialogResult;
    set 
    { 
      this.dialogResult = value; 
      OnPropertyChanged();
    }
  }

  private Func<DialogViewModel, Task> responseCallbackAsync;   
  public Func<DialogViewModel, Task> ResponseCallbackAsync
  {
    get => this.responseCallbackAsync;
    set 
    { 
      this.responseCallbackAsync = value; 
      OnPropertyChanged();
    }
  }

  public event EventHandler InteractionCompleted;
  protected virtual void OnInteractionCompleted()
  {
    this.InteractionCompleted?.Invoke(this, EventArgs.Empty);
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}
public class FileExistsDialogViewModel : DialogViewModel
{
  public FileExistsDialogViewModel(string message, string title) : base(message, title)
  { 
  }
  public FileExistsDialogViewModel(string message, string title, Func<DialogViewModel, Task> sendResponseCallbackAsync) : base(message, title, sendResponseCallbackAsync)
  { 
  }
  public FileExistsDialogViewModel(string message, string title, ImageSource titleBarIcon, Func<DialogViewModel, Task> sendResponseCallbackAsync) : base(message, title, titleBarIcon, sendResponseCallbackAsync)
  { 
  }
}
public enum DialogResult
{
  None = 0, Accepted, Denied, Aborted
}
public class RelayCommand : ICommand
{
  #region Fields 
  readonly Action<object> _execute;
  readonly Predicate<object> _canExecute;
  #endregion // Fields 
  #region Constructors 
  public RelayCommand(Action<object> execute) : this(execute, null) { }
  public RelayCommand(Action<object> execute, Predicate<object> canExecute)
  {
    if (execute == null)
    {
      throw new ArgumentNullException("execute");
    }

    this._execute = execute; this._canExecute = canExecute;
  }
  #endregion // Constructors 
  #region ICommand Members 
  [DebuggerStepThrough]
  public bool CanExecute(object parameter)
  {
    return this._canExecute == null ? true : this._canExecute(parameter);
  }
  public event EventHandler CanExecuteChanged
  {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
  }
  public void Execute(object parameter) { this._execute(parameter); }
  #endregion // ICommand Members 
}
<Application x:Class="Main.App"
             Startup="RunApplication">
    <Application.Resources>
      <ViewModel x:Key="MainViewModel />

      <Viewbox x:Key="WarningIcon"
               x:Shared="False">
        <ContentControl FontFamily="Segoe MDL2 Assets"
                        Content="&#xE814;" />
      </Viewbox>
      <Viewbox x:Key="WarningLightIcon"
               x:Shared="False">
        <ContentControl FontFamily="Segoe MDL2 Assets"
                        Content="&#xE7BA;" />
      </Viewbox>

      <!-- 
        Implicit DataTemplate that applies to types of FileExistsDialogViewModel.
        You can replace or modify it. 
        Just wire every dialog Button.Command to the 
        DialogViewModel.SendResponseCommand (reference via DataContext of this DataTemplate)
        and pass in a DialogResult enum value to the Button.CommandParameter
      -->
      <DataTemplate DataType="{x:Type FileExistsDialogViewModel}">
        <Grid Margin="12">
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
          </Grid.RowDefinitions>
          <StackPanel Grid.Row="0"
                      Orientation="Horizontal"
                      Margin="0,0,48,24">
            <Grid Margin="0,0,16,0">
              <ContentControl Panel.ZIndex="1"
                              Content="{StaticResource WarningIcon}"
                              VerticalAlignment="Center"
                              Height="32"
                              Foreground="Orange"
                              Background="Black" />
              <ContentControl Panel.ZIndex="2"
                              Content="{StaticResource WarningLightIcon}"
                              VerticalAlignment="Center"
                              Height="32"
                              Margin="0,4,0,0" />
            </Grid>
            <TextBlock Text="{Binding Message}" />
          </StackPanel>
          <StackPanel Grid.Row="1"
                      FocusManager.FocusedElement="{Binding ElementName=CancelButton}"
                      Orientation="Horizontal"
                      HorizontalAlignment="Right">
            <Button Content="Yes"
                    Padding="0"
                    Command="{Binding SendResponseCommand}"
                    CommandParameter="{x:Static DialogResult.Accepted}"
                    Margin="0,0,16,0" />
            <Button x:Name="CancelButton"
                    Content="No"
                    IsCancel="True"
                    IsDefault="True"
                    BorderThickness="3"
                    Padding="0"
                    Command="{Binding SendResponseCommand}"
                    CommandParameter="{x:Static DialogResult.Denied}" />
          </StackPanel>
        </Grid>
      </DataTemplate>
  </Application.Resources>
</Application>
class MainWindowViewModel
{
  public void ShowFileAlreadyExistsDialog()
  {  
    // Initialize the DialogViewModel implementation for the File Exists dialog
    var dialogTitleBarIcon = new BitmapImage(new Uri("../../logo.ico", UriKind.Relative));
    if (titleBarIcon.CanFreeze)
    {
      titleBarIcon.Freeze();
    }

    var message = "File exists. Do you want to replace it?";
    var dialogTitle = "File Exists";

    // Set the continuation callback which will be invoked once the dialog closed
    DialogViewModel fileExistsdialogViewModel = new FileExistsDialogViewModel(
      message, 
      dialogTitle, 
      dialogTitleBarIcon, 
      dialogViewModel => HandleFileExistsDialogResponseAsync(dialogViewModel, filePath, settingsData));

    // Show the dialog by setting the DialogViewModel property to an instance of DialogViewModel
    this.DialogViewModel = fileExistsdialogViewModel;
  }

  // Continuation callback. Will be invoked once the dialog closed. 
  // The parameter is the previously created FileExistsDialogViewmodel containing data set from the dialog.
  private async Task HandleFileExistsDialogResponseAsync(DialogViewModel dialogViewModel, string filePath, string settingsData)
  {
    if (dialogViewModel.DialogResult == DialogResult.Accepted)
    {
      // Example method
      await SaveFileAsync(filePath, settingsData);
    }
  }

  private DialogViewModel dialogViewModel;   
  public DialogViewModel DialogViewModel
  {
    get => this.dialogViewModel;
    set 
    { 
      this.dialogViewModel = value; 
      OnPropertyChanged();
    }
  }
}
<Window x:Class="BionicCode.BionicNuGetDeploy.Main.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"        
        xmlns:dialog="clr-namespace:BionicUtilities.Net.Dialog;assembly=BionicUtilities.Net"
        mc:Ignorable="d"
        Title="MainWindow"
        DataContext="{StaticResource MainViewModel}
        Dialog.DialogDataContext="{Binding DialogViewModel}">
</Window>    
Related Posts Related Posts :
  • WPF InvalidateMeasure not called during or after animation
  • How can I define how many spaces a TAB jumps in a XAML TextBox?
  • The calling thread must be STA, because many UI components require this
  • WPF Popup hiding problem
  • ModelVisual3D vs Model3DGroup
  • Composite Commands Not Working
  • WPF ListBox Scroll to end automatically
  • 'Default' text for templated combo box
  • MDI and WPF Ribbon
  • WPF FontSize style hangs / freezes / stops responding
  • WPF: Textbox width guidelines
  • WPF mediaelement
  • Embedding WinForms Graph in WPF Window
  • WPF: Focus in a Window and UserControl
  • How can I stretch bitmap in WPF without smoothing pixels
  • Changing DataTemplate TextBlock Property at Runtime
  • Image source using project resource (WPF)
  • WPF combobox colors
  • WPF: Window stays minimized even when setting WindowState explicitly
  • WPF: Drag/Drop to re-order grid and jiggle
  • Dynamically updating a WPF ListView after changes
  • WPF: How do I implement a stretch transform?
  • intercept RelativeSource FindAncestor
  • WPF Listbox wont scroll Vertical
  • WPF window on closing
  • WPF UserControl is not drawn when overriding MeasureOverride and ArrangeOverride
  • Master/Detail UI Best Practices?
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org