[英]A Usercontrol with just a TextBlock. How do I expose the TextWrapping property to the consumer?
[英]How do I expose an ICommand property from a UserControl
我有一個MainControl應用程序正在使用的UserControl。 UserControl在完成內部任務后觸發事件。 我現在希望MainWindow應用程序通過ICommand處理此事件。
我假定可以通過在UserControl上實現ICommand作為DependencyObject來實現,然后再由MainWindow綁定到IControl。
我離目標很遠嗎?
有示例顯示如何使用MVVM做到這一點嗎?
謝謝
另一種方法是創建附加到由UserControl觸發的事件的行為。 在事件處理程序內部,該行為將執行ViewModel的ICommand
。
在這里,您可以找到一個附加到FrameworkElement
SizeChanged
事件的自定義行為:
public class FrameworkElementSizeChangedBehaviour
{
public static void SetFrameworkElementSize(DependencyObject obj, ICommand value)
{
obj.SetValue(FrameworkElementSizeChangedBehaviour.FrameworkElementSizeProperty, value);
}
public static readonly DependencyProperty FrameworkElementSizeProperty = DependencyProperty.RegisterAttached("FrameworkElementSize",
typeof(ICommand),
typeof(FrameworkElementSizeChangedBehaviour),
new UIPropertyMetadata(FrameworkElementSizeChanged));
private static void FrameworkElementSizeChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = target as FrameworkElement;
if (element == null)
throw new InvalidOperationException();
if ((e.NewValue != null) && (e.OldValue == null))
{
element.SizeChanged += element_SizeChanged;
}
else if ((e.NewValue == null) && (e.OldValue != null))
{
element.SizeChanged -= element_SizeChanged;
}
}
static void element_SizeChanged(object sender, SizeChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = (ICommand)element.GetValue(FrameworkElementSizeChangedBehaviour.FrameworkElementSizeProperty);
if (command != null)
{
Size args = new Size(element.ActualWidth, element.ActualHeight);
if (command.CanExecute(args))
{
command.Execute(args);
}
}
}
}
然后,您可以通過以下方式將行為附加到UserControl:
<MyUserControl mybehaviournamespace:FrameworkElementSizeBehaviour.FrameworkElementSize="{Binding ICommandToBeExecuted}" />
其中ICommandToBeExecuted
表示在觸發UserControl事件時要調用的ViewModel的ICommand
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.