2012-12-02 68 views

回答

4

這裏是我使用的解決方案:

public class Clip 
{ 
    public static bool GetToBounds(DependencyObject depObj) 
    { 
     return (bool)depObj.GetValue(ToBoundsProperty); 
    } 

    public static void SetToBounds(DependencyObject depObj, bool clipToBounds) 
    { 
     depObj.SetValue(ToBoundsProperty, clipToBounds); 
    } 

    /// <summary> 
    /// Identifies the ToBounds Dependency Property. 
    /// <summary> 
    public static readonly DependencyProperty ToBoundsProperty = 
     DependencyProperty.RegisterAttached("ToBounds", typeof(bool), 
     typeof(Clip), new PropertyMetadata(false, OnToBoundsPropertyChanged)); 

    private static void OnToBoundsPropertyChanged(DependencyObject d, 
     DependencyPropertyChangedEventArgs e) 
    { 
     FrameworkElement fe = d as FrameworkElement; 
     if (fe != null) 
     { 
      ClipToBounds(fe); 

      // whenever the element which this property is attached to is loaded 
      // or re-sizes, we need to update its clipping geometry 
      fe.Loaded += new RoutedEventHandler(fe_Loaded); 
      fe.SizeChanged += new SizeChangedEventHandler(fe_SizeChanged); 
     } 
    } 

    /// <summary> 
    /// Creates a rectangular clipping geometry which matches the geometry of the 
    /// passed element 
    /// </summary> 
    private static void ClipToBounds(FrameworkElement fe) 
    { 
     if (GetToBounds(fe)) 
     { 
      fe.Clip = new RectangleGeometry() 
      { 
       Rect = new Rect(0, 0, fe.ActualWidth, fe.ActualHeight) 
      }; 
     } 
     else 
     { 
      fe.Clip = null; 
     } 
    } 

    static void fe_SizeChanged(object sender, SizeChangedEventArgs e) 
    { 
     ClipToBounds(sender as FrameworkElement); 
    } 

    static void fe_Loaded(object sender, RoutedEventArgs e) 
    { 
     ClipToBounds(sender as FrameworkElement); 
    } 
} 

發現here

1

我更喜歡這裏的 '夾' 屬性是一些XAML

<Grid Width="100" Height="50"> 
    <Grid.Clip> 
     <RectangleGeometry Rect="0 0 100 50"/> 
    </Grid.Clip> 
</Grid> 

的 '矩形' 的參數屬性是:Rect =「xy寬度高度」

希望它有幫助

問候

2

這在WinRTXamlToolkit(https://github.com/xyzzer/WinRTXamlToolkit)來實現,其也可作爲NuGet包。

添加到XAML頭:

xmlns:extensions="using:WinRTXamlToolkit.Controls.Extensions" 

然後,例如在XAML Canvas組件

<Canvas extensions:FrameworkElementExtensions.ClipToBounds="True"/> 
相關問題