3 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
一般來(lái)說(shuō):
你的 MVVM 視圖模型應(yīng)該只包含數(shù)據(jù)和命令。當(dāng)然有很多例外,但請(qǐng)記住,基本上,它應(yīng)該只包含與視圖相關(guān)的命令和項(xiàng)目。
當(dāng)事件處理程序應(yīng)用于組件時(shí),我看到了很多關(guān)于這一點(diǎn)的困惑。事情是; 當(dāng)您在視圖模型中放置 UI 組件的事件處理程序時(shí),視圖模型綁定到視圖的實(shí)際實(shí)現(xiàn)(使用 UI 組件),而不是一般的“視圖”。
根據(jù)經(jīng)驗(yàn); 你應(yīng)該能夠復(fù)制你的視圖模型并在另一個(gè)實(shí)現(xiàn)中使用它,它應(yīng)該只是編譯。它不應(yīng)該包含對(duì) UI 元素本身的引用,或者通過(guò)事件處理等間接引用。
所以,是的,您應(yīng)該將這些事件處理程序放在代碼隱藏中,或者找到一個(gè)能夠在視圖/XAML 中處理它的框架或組件。從這樣的事件中調(diào)用命令完全沒(méi)問(wèn)題。更實(shí)用的方法會(huì)說(shuō):將它們放在最有效的地方,并使您的代碼最易讀/易維護(hù)。如果你理解了 MVVM 的概念,你就會(huì)盡量減少這些混合模型的出現(xiàn),這通常就足夠了。

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
我會(huì)用附加屬性做這樣的事情。例如,對(duì)于 FileDrop,我將實(shí)現(xiàn)一個(gè)附加屬性,如下所示:
public static class WindowExtensions
{
public static readonly DependencyProperty ReadScriptFilesCommandProperty = DependencyProperty.RegisterAttached(
"ReadScriptFilesCommand",
typeof(ICommand),
typeof(WindowExtensions),
new PropertyMetadata(default(ICommand), OnReadScriptFilesCommandChanged));
private static void OnReadScriptFilesCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Window window = d as Window;
if (window == null)
return;
if (e.NewValue is ICommand)
{
window.Drop += WindowOnDrop;
}
if (e.OldValue != null)
{
window.Drop -= WindowOnDrop;
}
}
private static void WindowOnDrop(object sender, DragEventArgs e)
{
Window window = sender as Window;
if (window == null)
return;
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
ICommand readScriptFilesCommand = GetReadScriptFilesCommand(window);
readScriptFilesCommand.Execute(files);
}
}
public static void SetReadScriptFilesCommand(DependencyObject element, ICommand value)
{
element.SetValue(ReadScriptFilesCommandProperty, value);
}
public static ICommand GetReadScriptFilesCommand(DependencyObject element)
{
return (ICommand)element.GetValue(ReadScriptFilesCommandProperty);
}
}
所以你可以在你Window的視圖中設(shè)置它并將它鏈接到ICommand你的視圖模型中。該命令采用string[]并執(zhí)行邏輯。
- 3 回答
- 0 關(guān)注
- 167 瀏覽
添加回答
舉報(bào)