2013-03-11 76 views
1

有沒有辦法重用WPF視圖使用它與Caliburn.Micro?如何重用wpf視圖?

在示例中,我有一個帶有SaveAndClose和Cancel按鈕的DetailViewBase.xaml。現在我想在PersonView(Model)中使用DetailViewModelBase和XAML。

我希望這個問題很明顯。

回答

2

如果我的假設是正確的,我想你的意思是,你想從幾個到「撰寫」一個更復雜的視圖更簡單的視圖模型。您可以從視圖模型繼承,但顯然視圖模型一次只能有一個活動視圖。

然而,使用綁定您可以撰寫多的ViewModels並使它們全部呈現各自的意見,共同做出更復雜的UI

例如

甲VM與保存/取消按鈕

public class ActionsViewModel 
{ 
    public void Save() 
    { 
    } 

    public void Cancel() 
    { 
    } 
} 

的相應的視圖:

<UserControl> 
    <StackPanel Orientation="Horizontal"> 
     <Button x:Name="Save">Save</Button> 
     <Button x:Name="Cancel">Cancel</Button> 
    </StackPanel> 
</UserControl> 

其構成自身與ActionsViewModel

public class ComposedViewModel 
{ 
    public ActionsViewModel ActionsView 
    { 
     get; set; 
    } 

    public ComposedViewModel() 
    { 
     ActionsView = new ActionsViewModel(); 
    }  

    public void DoSomething() 
    { 
    } 
} 

觀另一種觀點:

<UserControl> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock>Hello World</TextBlock> 
     <Button x:Name="DoSomething">Do Something</Button> 
     <ContentControl x:Name="ActionsView" /> 
    </StackPanel> 
</UserControl> 

當您使用約定綁定(或使用附加屬性)綁定ContentControl時,CM將自動綁定虛擬機到DataContext並連接視圖。這樣,您可以將多個虛擬機組合成一個更復雜的功能。

此外,由於動作消息冒泡的 - 如果你要刪除的ActionsViewModel的「確定」和「取消」的實施,並把它們放在ComposedViewModel實施,動作消息會泡到ComposedViewModel實例和火在那裏的方法

eg

public class ActionsViewModel 
{ 
    // Remove the command handlers 
} 


public class ComposedViewModel 
{ 
    public ActionsViewModel ActionsView 
    { 
     get; set; 
    } 

    public ComposedViewModel() 
    { 
     ActionsView = new ActionsViewModel(); 
    }  

    public void DoSomething() 
    { 
    } 

    // CM will bubble the messages up so that these methods handle them when the user clicks on the buttons in the ActionsView 
    public void Save() 
    { 
    } 

    public void Cancel() 
    { 
    } 
} 

編輯:

對不起,我忘了這一點 - 根據約定綁定不允許消息泡沫,但你可以只使用Message.Attach附加屬性的這個工作:

// Make sure you include the caliburn namespace: 
<UserControl xmlns:cal="http://www.caliburnproject.org"> 
    <StackPanel Orientation="Horizontal"> 
     <Button x:Name="Save" cal:Message.Attach="Save">Save</Button> 
     <Button x:Name="Cancel" cal:Message.Attach="Cancel">Cancel</Button> 
    </StackPanel> 
</UserControl> 
+0

嗨Charleh, 你是對的。這是我正在尋找,但emoving保存並取消並將其放置到ComposedVM不適合我。它只是在ActionsVM中工作。 有沒有我沒有得到的配置? – 2013-03-12 10:42:03

+0

對不起,我應該糾正後 - 冒泡將不會與約定指定的消息(因爲什麼都沒有發現的視圖虛擬機綁定到並沒有行動創建)。你需要在視圖代碼中專門創建一個actionmessage來獲取冒泡 - 我會更新答案 – Charleh 2013-03-12 10:54:21

0

您可以視圖模型綁定到視圖明確使用這樣的代碼:

cal:Bind.Model={Binding DetailViewModelBase}