Skip to content

Commit 00f73ab

Browse files
committed
when using command parameter to pass dialog content, inherit data context from the button #124
1 parent 1801991 commit 00f73ab

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

MainDemo.Wpf/Dialogs.xaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@
105105
wpf:DialogHost.DialogClosingAttached="Sample2_DialogHost_OnDialogClosing"
106106
Width="128">
107107
<Button.CommandParameter>
108-
<StackPanel Margin="16">
108+
<StackPanel Margin="16" DataContext="HelloWorld">
109109
<ProgressBar Style="{DynamicResource MaterialDesignCircularProgressBar}" HorizontalAlignment="Center" Margin="16" IsIndeterminate="True" Value="0" />
110110
<Button Style="{StaticResource MaterialDesignFlatButton}" IsCancel="True"
111111
Command="{x:Static wpf:DialogHost.CloseDialogCommand}"

MaterialDesignThemes.Wpf/DialogHost.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,20 @@ private void OpenDialogHandler(object sender, ExecutedRoutedEventArgs executedRo
437437
if (executedRoutedEventArgs.Parameter != null)
438438
{
439439
AssertTargetableContent();
440-
DialogContent = executedRoutedEventArgs.Parameter;
440+
441+
//TODO enhancement: make the following configurable, so that the data context can be pulled from the dialog host if desired.
442+
// (leave the current behaviour as the default; most developers will find this logical, as the data context will "inherit" from button containing the content)
443+
444+
var contentElement = executedRoutedEventArgs.Parameter as FrameworkElement;
445+
var senderElement = executedRoutedEventArgs.OriginalSource as FrameworkElement;
446+
if (contentElement != null && senderElement != null && contentElement.DataContext == null && BindingOperations.GetBindingExpression(contentElement, DataContextProperty) == null)
447+
{
448+
DialogContent = executedRoutedEventArgs.Parameter;
449+
contentElement.SetCurrentValue(DataContextProperty, senderElement.DataContext);
450+
}
451+
else
452+
DialogContent = executedRoutedEventArgs.Parameter;
453+
441454
}
442455

443456
SetCurrentValue(IsOpenProperty, true);

0 commit comments

Comments
 (0)