2010-10-18 120 views

回答

3

不能使用畫布脫身,但是,這並不意味着你必須遵守畫布怎麼安排事情

我已經創建了幾個行爲的,可以對您有用

第一個是:。

[TypeConstraint(typeof(Canvas))] 
public class MouseCursorAction : TargetedTriggerAction<UIElement> 
{ 

    protected override void Invoke(object parameter) 
    { 
    } 

    protected override void OnAttached() 
    { 
     var canvas = AssociatedObject as Canvas; 
     if (canvas == null) { return; } 
     canvas.MouseMove += new MouseEventHandler(canvas_MouseMove); 
     canvas.MouseEnter += new MouseEventHandler(canvas_MouseEnter); 
     canvas.MouseLeave += new MouseEventHandler(canvas_MouseLeave); 
    } 

    void canvas_MouseLeave(object sender, MouseEventArgs e) 
    { 
     Target.Visibility = Visibility.Collapsed; 
    } 

    void canvas_MouseEnter(object sender, MouseEventArgs e) 
    { 
     Target.Visibility = Visibility.Visible; 
    } 

    void canvas_MouseMove(object sender, MouseEventArgs e) 
    { 
     var canvas = sender as Canvas; 
     var positionInCanvas = e.GetPosition(canvas); 
     Canvas.SetTop(Target, positionInCanvas.Y); 
     Canvas.SetLeft(Target, positionInCanvas.X); 
    } 
} 

有了這個行爲,你可以轉換你的鼠標光標中的任何UIElement。只需將其設置爲畫布並選擇您想要鼠標光標的目標。

現在,爲您解決佈局問題我已經創造了這個其他行爲:

[TypeConstraint(typeof(Canvas))] 
public class FillCanvasAction : TargetedTriggerAction<FrameworkElement> 
{ 

    protected override void Invoke(object parameter) 
    { 
    } 

    protected override void OnAttached() 
    { 
     var canvas = AssociatedObject as Canvas; 
     if (canvas == null) { return; } 
     canvas.SizeChanged += new SizeChangedEventHandler(Target_SizeChanged); 
    } 

    void Target_SizeChanged(object sender, SizeChangedEventArgs e) 
    { 
     var element = Target; 
     if (element == null) { return; } 

     var canvas = sender as Canvas; 

     element.Width = canvas.ActualWidth; 
     element.Height = canvas.ActualHeight; 
     Canvas.SetTop(element, 0); 
     Canvas.SetLeft(element, 0); 
    } 
} 

這種現象,當連接到父畫布上,將調整目標FrameworkElement的(例如網格),以規模父Canvas。這意味着您可以在此FrameworkElement內創建自己的自定義佈局,而無需擔心Canvas處理佈置的方式。

然後在你的XAML可以做這樣的事情:

<Grid x:Name="LayoutRoot" Cursor="None"> 
    <Canvas x:Name="canvas" Background="Black"> 
     <i:Interaction.Triggers> 
      <i:EventTrigger EventName="MouseEnter"> 
       <local:MouseCursorAction TargetObject="{Binding ElementName=cursorImage}"/> 
      </i:EventTrigger> 
      <i:EventTrigger> 
       <local:FillCanvasAction TargetObject="{Binding ElementName=grid}"/> 
      </i:EventTrigger> 
     </i:Interaction.Triggers> 
     <Grid x:Name="grid" Background="White" Width="600" Height="400"> 
      <!-- Create your layout here --> 
     </Grid> 
     <Image x:Name="cursorImage" Height="50" Width="50" Source="mouse_cursor.png"/> 
    </Canvas> 
</Grid> 

您可以得到完整的工作代碼here

免責聲明:嚴格地說這種行爲應該使用弱事件處理,以避免實施內存泄漏;然而這個實現超出了這個答案的範圍。您可以找到關於弱事件處理的更多信息,以及您是否需要它以用於本網站上的項目。

+0

這真是一個很好的答案!謝謝! – Palantir 2010-10-20 08:07:06

相關問題