gpt4 book ai didi

wpf - 从 ViewModel 触发 UIElement 的操作

转载 作者:行者123 更新时间:2023-12-03 10:56:05 25 4
gpt4 key购买 nike

我已经实现了Wiesław Šoltés ' 真棒ZoomBorder ,但我在 WPF 和 MVVM 方面有点挣扎。为了问题的完整性,ZoomBorderUIElement继承自 Border并为用户提供缩放和平移继承边框内容的可能性。它还具有重置缩放和平移的能力。
我想做ZoomBorder对某个 View 模型发布的事件使用react,以便在发布该事件时,ZoomBorder重置缩放。在我的实现中,ZoomBorderDataContextContentViewModel ,它有一个 IEventAggregator (Prism.Events) 通过 Autofac 注入(inject)。理想情况下,我希望将事件聚合器直接注入(inject) ZoomBorder ,以便它可以订阅事件,但我不能,因为构造函数需要是无参数的。
所以ContentViewModel必须订阅该事件,但我将如何调用 ZoomBorderReset来自 ContentViewModel 的方法?我知道我会违反 MVVM,但我不知道该怎么做。我想过制作ZoomBorder公开一个 Command通过依赖属性,然后是 Reset代码必须在 View 模型上,但它不能。

最佳答案

您可以使用 ServiceLocator在 View 或控件内部解析容器中的类型。

public ZoomBorder()
{
_eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
}
如果您使用 AutoFac 和没有 Prism 的事件聚合器,您可以使用包 Autofac.Extras.CommonServiceLocatorregister your containerServiceLocator .
var builder = new ContainerBuilder();
var container = builder.Build();

var csl = new AutofacServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => csl);

关于wpf - 从 ViewModel 触发 UIElement 的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63387717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com