0
votes

I want to create a customized import dialog and therefore I created a window with some stuff. In order to make this import dialog modal, I'm using the ShowDialog() method. Up to now everything works as expected. My code looks like:

var dialogresult = new MyImportDialog().ShowDialog();
if(dialogresult.HasValue && dialogresult.Value)
{
   Console.WriteLine("Import");

}

But when I try to use this dialog twice, got a ArgumentException because my static DependencyProperties got registered a second time. So I tried not to delete my import dialog and use it a second time.

private MyImportDialog _myImportDialog;

private void OnImportClick(object sender, RoutedEventArgs e)
{
     if (_myImportDialog== null)
          _myImportDialog= new MyImportDialog ();

     var dialogresult = _myImportDialog.ShowDialog();
     if(dialogresult.HasValue && dialogresult.Value)
     {
          Console.WriteLine("Import");              
     }
}

Now I got an InvalidOperationException(Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.). But the ShowDialog method has an remark: "Opens a window and returns only when the newly opened window is closed."

So my next idea was to register for the closing event in my import dialog and then unregister my DependecyProperties. Unfortunately there is no official way doing this. The only thing I found was this: Any way to un-register a WPF dependency property?.

But the solution is (in my opinion) a little bit dirty and the author warned not to use this code in productive environment.

So, is there another more cleaner solution to use a modal window twice?

Thanking you in anticipation.

Edit: This code shows one Dependency Property I'm using:

public DependencyProperty ClearProperty = 
     DependencyProperty.Register("Clear", typeof (bool),
                                 typeof (MyImportDialog), 
                                 new PropertyMetadata(true));
    /// <summary>
    /// Indicates whether view should be cleard before importing new image stack.
    /// </summary>
    public bool Clear { 
         get { return (bool) GetValue(ClearProperty); } 
         set { SetValue(ClearProperty, value);} 
    }
1
How are you setting the DataContext of the Window? Can you post your XAML.Aaron McIver

1 Answers

0
votes

It sounds like your static dependency properties are not defined as static members. Otherwise they would only be initialized when the static initializer was executed (i.e. the first time the class was referenced). Can you paste the DependencyProperty.Register code? DependencyProperty fields are supposed to be declared statically.

public static DependencyProperty ClearProperty =  
 DependencyProperty.Register("Clear", typeof (bool), 
                             typeof (MyImportDialog),  
                             new PropertyMetadata(true));