2012-03-23 85 views
2

你好,我有一些按鈕隨機分配在我的WPF應用程序,像這樣:設置選項來查看框

partial class Window1 
{ 

    private void button3_Click(object sender, RoutedEventArgs e) 
    { 
     MessageBox.Show("action 3"); 
    } 
    void button2Click(object sender, RoutedEventArgs e) 
    { 
     MessageBox.Show("action 2"); 
    } 
    void button1Click(object sender, RoutedEventArgs e) 
    { 
     MessageBox.Show("action 1"); 
    } 

    public Window1() 
    { 
     this.InitializeComponent(); 
     populateButtons(); 
    } 

    public void populateButtons() 
    { 
     double xPos; 
     double yPos; 


     Random ranNum = new Random(); 
     foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click }) 
     { 

      Button foo = new Button(); 


      Style buttonStyle = Window.Resources["CurvedButton"] as Style; 
      int sizeValue = 100; 

      foo.Width = sizeValue; 
      foo.Height = sizeValue; 

      xPos = ranNum.Next(200); 
      yPos = ranNum.Next(250); 


      foo.HorizontalAlignment = HorizontalAlignment.Left; 
      foo.VerticalAlignment = VerticalAlignment.Top; 
      foo.Margin = new Thickness(xPos, yPos, 0, 0); 
      foo.Style = buttonStyle; 

      foo.Click += routedEventHandler; 

      LayoutRoot.Children.Add(foo); 
     } 
    } 
} 

}

我設置了填充的按鈕,像這樣的區域:

 int xPos; 
     int yPos; 

      xPos = ranNum.Next(239); 
      yPos = ranNum.Next(307); 


      foo.HorizontalAlignment = HorizontalAlignment.Left; 
      foo.VerticalAlignment = VerticalAlignment.Top; 
      foo.Margin = new Thickness(xPos, yPos, 0, 0); 

我現在更願意做的是設置這個區域的視圖框命名爲viewbox1(original eh!);)

有沒有辦法在後面的代碼中做到這一點?

XAML:

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xml:lang="en-US" 
    x:Class="DynamicButtons.Window1" 
    x:Name="Window" 
    Title="Dynamic Buttons" 
    WindowState="Normal" WindowStyle="None" AllowsTransparency="True" Background="Transparent" 
    Width="840" Height="600" Icon="shape_group.png"> 
    <Window.Resources> 
      <Style x:Key="CurvedButton" BasedOn="{x:Null}" TargetType="{x:Type Button}"> 

       <Setter Property="Template"> 
        <Setter.Value> 
         <ControlTemplate TargetType="{x:Type Button}"> 
          <ControlTemplate.Resources> 
           <Storyboard x:Key="OnMouseMove1"> 
            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"> 
             <SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFFFFFF"/> 
             <SplineColorKeyFrame KeyTime="00:00:00.3000000" Value="#7CE1DBDB"/> 
            </ColorAnimationUsingKeyFrames> 
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"> 
             <SplineDoubleKeyFrame KeyTime="00:00:00" Value="1"/> 
             <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="1.66"/> 
            </DoubleAnimationUsingKeyFrames> 
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"> 
             <SplineDoubleKeyFrame KeyTime="00:00:00" Value="1"/> 
             <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="1.66"/> 
            </DoubleAnimationUsingKeyFrames> 
           </Storyboard> 
           <Storyboard x:Key="OnMouseLeave1"> 
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"> 
             <SplineDoubleKeyFrame KeyTime="00:00:00.8000000" Value="1.78"/> 
             <SplineDoubleKeyFrame KeyTime="00:00:01" Value="1"/> 
            </DoubleAnimationUsingKeyFrames> 
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"> 
             <SplineDoubleKeyFrame KeyTime="00:00:00.8000000" Value="1.78"/> 
             <SplineDoubleKeyFrame KeyTime="00:00:01" Value="1"/> 
            </DoubleAnimationUsingKeyFrames> 
           </Storyboard> 
           <Storyboard x:Key="OnClick1"> 
            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"> 
             <SplineColorKeyFrame KeyTime="00:00:00.2000000" Value="#FFFFFFFF"/> 
             <SplineColorKeyFrame KeyTime="00:00:00.3000000" Value="#BFA0D1E2"/> 
            </ColorAnimationUsingKeyFrames> 
           </Storyboard> 
          </ControlTemplate.Resources> 
          <Grid> 
           <Rectangle RenderTransformOrigin="1,1" Fill="#3FFFFFFF" Stroke="{x:Null}" RadiusX="11" RadiusY="11" x:Name="rectangle"> 
            <Rectangle.RenderTransform> 
             <TransformGroup> 
              <ScaleTransform ScaleX="1" ScaleY="1"/> 
              <SkewTransform AngleX="0" AngleY="0"/> 
              <RotateTransform Angle="0"/> 
              <TranslateTransform X="0" Y="0"/> 
             </TransformGroup> 
            </Rectangle.RenderTransform> 
           </Rectangle> 
           <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/> 
          </Grid> 
          <ControlTemplate.Triggers> 
           <EventTrigger RoutedEvent="ButtonBase.Click"> 
            <BeginStoryboard x:Name="OnClick1_BeginStoryboard" Storyboard="{StaticResource OnClick1}"/> 
           </EventTrigger> 
           <EventTrigger RoutedEvent="Mouse.MouseLeave"> 
            <BeginStoryboard x:Name="OnMouseLeave1_BeginStoryboard" Storyboard="{StaticResource OnMouseLeave1}"/> 
           </EventTrigger> 
           <EventTrigger RoutedEvent="FrameworkElement.Loaded"/> 
           <EventTrigger RoutedEvent="Mouse.MouseEnter"> 
            <BeginStoryboard x:Name="OnMouseMove1_BeginStoryboard" Storyboard="{StaticResource OnMouseMove1}"/> 
           </EventTrigger> 
           <Trigger Property="IsFocused" Value="True"/> 
           <Trigger Property="IsDefaulted" Value="True"/> 
           <Trigger Property="IsMouseOver" Value="True"/> 
           <Trigger Property="IsPressed" Value="True"/> 
           <Trigger Property="IsEnabled" Value="False"/> 
          </ControlTemplate.Triggers> 
         </ControlTemplate> 
        </Setter.Value> 
       </Setter> 

       <Setter Property="Background"> 
        <Setter.Value> 
         <LinearGradientBrush EndPoint="0,1" StartPoint="0,0"> 
          <GradientStop Color="#FFF3F3F3" Offset="0"/> 
          <GradientStop Color="#FFEBEBEB" Offset="0.5"/> 
          <GradientStop Color="#FFDDDDDD" Offset="0.5"/> 
          <GradientStop Color="#E1CDCDCD" Offset="1"/> 
         </LinearGradientBrush> 
        </Setter.Value> 
       </Setter> 
      </Style> 
     </Window.Resources> 
    <Window.Triggers> 
     <EventTrigger RoutedEvent="FrameworkElement.Loaded"/> 
    </Window.Triggers> 
     <Grid x:Name="LayoutRoot"> 
     <Grid Name="MainLayoutGrid" Background="#2b2b2b"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="4" /> 
       <ColumnDefinition Width="*" /> 
       <ColumnDefinition Width="4" /> 
      </Grid.ColumnDefinitions> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="4" /> 
       <RowDefinition Height="25" /> 
       <RowDefinition Height="*" /> 
       <RowDefinition Height="4" /> 
      </Grid.RowDefinitions> 
      <Grid Grid.Column="1" Grid.Row="1" Name="TitleGrid"> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="2"/> 
        <RowDefinition Height="*"/> 
        <RowDefinition Height="4"/> 
       </Grid.RowDefinitions> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="Auto"/> 
        <ColumnDefinition Width="*"/> 
        <ColumnDefinition Width="100"/> 
       </Grid.ColumnDefinitions> 
       <Grid Grid.Row="1" Grid.Column="0"> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="20"/> 
         <ColumnDefinition Width="4"/> 
         <ColumnDefinition Width="Auto"/> 
        </Grid.ColumnDefinitions> 
        <Image Grid.Column="0" Name="ImageIcon" Stretch="Uniform"/> 
        <TextBlock Grid.Column="2" Name="Titleblk" Foreground="White">Wanna be Title</TextBlock> 

       </Grid> 
       <Grid Grid.Row="0" Grid.Column="2" Grid.RowSpan="2"> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="25"/> 
         <ColumnDefinition Width="25"/> 
         <ColumnDefinition Width="*"/> 
        </Grid.ColumnDefinitions> 
        <Button Name="btnMin" Grid.Column="1" Grid.ColumnSpan="2" Margin="8,4,42,-4"> 
         <Button.RenderTransform> 
          <ScaleTransform ScaleX="0.8" ScaleY="0.8"></ScaleTransform> 
         </Button.RenderTransform> 
         <Button.Clip> 
          <RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,18,20" /> 
         </Button.Clip> 
        </Button> 
        <Button Name="btnMax" Grid.Column="2" Margin="2,4,23,-4"> 
         <Button.RenderTransform> 
          <ScaleTransform ScaleX="0.8" ScaleY="0.8"></ScaleTransform> 
         </Button.RenderTransform> 
         <Button.Clip> 
          <RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,18,20" /> 
         </Button.Clip> 
        </Button> 
        <Button Name="btnClose" Grid.Column="2" Margin="24,0,6,0" BorderBrush="#00000000" BorderThickness="0" ClickMode="Press" Foreground="#00000000" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" OpacityMask="#82F8F8F8" VerticalAlignment="Stretch" VerticalContentAlignment="Center"> 
         <Button.Clip> 
          <RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,20,20" /> 
         </Button.Clip> 
        </Button> 
       </Grid> 
      </Grid> 

      <Grid Grid.Column="1" Grid.Row="2"> 
       <Grid.Background> 
        <LinearGradientBrush EndPoint="0.484,0.543" StartPoint="0.478,0.009"> 
         <GradientStop Color="Gray" Offset="1"/> 
         <GradientStop Color="DarkGray" Offset="0"/> 
        </LinearGradientBrush> 
       </Grid.Background> 
       <UniformGrid> 
        <Viewbox Height="364" Name="viewbox1" Width="363" VerticalAlignment="Stretch" Margin="6,0,441,164" /> 
       </UniformGrid> 
      </Grid> 
     </Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="*"/> 
     </Grid.ColumnDefinitions> 
     <!--<Canvas Height="284" HorizontalAlignment="Left" Margin="457,66,0,0" Name="canvas1" VerticalAlignment="Top" Width="300" />--> 
    </Grid> 

</Window> 

全碼:

namespace DynamicButtons 
{ 
    partial class Window1 
    { 

     void button3_Click(object sender, RoutedEventArgs e) 
     { 
      if (e.RoutedEvent == FrameworkElement.LoadedEvent) 
      { 
       ToolTip t = new ToolTip(); 
       t.Content = "Something helpful"; 
       ((Button)sender).ToolTip = t; 
       ((Button)sender).Content = "Hello"; 
       return; 
      } 
      MessageBox.Show("Hello you punk"); 
     } 
     void button2Click(object sender, RoutedEventArgs e) 
     { 
      //ToolTip t = new ToolTip(); 
      //t.Content = "Something helpful"; 
      //((Button)sender).ToolTip = t; 

      //MessageBox.Show("action 2"); 
     } 
     void button1Click(object sender, RoutedEventArgs e) 
     { 
      //ToolTip t = new ToolTip(); 
      //t.Content = "Something helpful"; 
      //((Button)sender).ToolTip = t; 
      ////Button b = new Button(); 
      //((Button)sender).Content = "Hello"; 
      ////b.ToolTip = t; 

      //MessageBox.Show("action 1"); 
     } 

     public Window1() 
     { 
      this.InitializeComponent(); 
      populateButtons(); 

     } 
     public void populateButtons() 
     { 
      double xPos; 
      double yPos; 

      UniformGrid grid = new UniformGrid(); 

      Viewbox viewBox = new Viewbox(); 
      viewBox.Name = "viewbox1"; 
      viewBox.Stretch = Stretch.Fill; 
      viewBox.Child = grid; 

      LayoutRoot.Children.Add(viewBox); 
      Random ranNum = new Random(); 
      foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click }) 
      { 
       Button foo = new Button(); 
       Style buttonStyle = Window.Resources["CurvedButton"] as Style; 
       int sizeValue = 100; 

       foo.Width = sizeValue; 
       foo.Height = sizeValue; 

       xPos = ranNum.Next(100); 
       yPos = ranNum.Next(150); 


       foo.HorizontalAlignment = HorizontalAlignment.Left; 
       foo.VerticalAlignment = VerticalAlignment.Top; 
       foo.Margin = new Thickness(xPos, yPos, 0, 0); 
       foo.Style = buttonStyle; 

       foo.Click += routedEventHandler; 
       foo.Loaded += routedEventHandler; 

       grid.Children.Add(foo); 
      } 
     } 

回答

1

的按鈕添加到視框,你可以只是這樣做:

public void populateButtons() 
    { 
     double xPos; 
     double yPos; 

     UniformGrid grid = new UniformGrid(); 
     viewbox1.Child = grid; 

     Random ranNum = new Random(); 
     foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click }) 
     { 
      Button foo = new Button(); 
      Style buttonStyle = Window.Resources["CurvedButton"] as Style; 
      int sizeValue = 100; 

      foo.Width = sizeValue; 
      foo.Height = sizeValue; 

      xPos = ranNum.Next(200); 
      yPos = ranNum.Next(250); 


      foo.HorizontalAlignment = HorizontalAlignment.Left; 
      foo.VerticalAlignment = VerticalAlignment.Top; 
      foo.Margin = new Thickness(xPos, yPos, 0, 0); 
      foo.Style = buttonStyle; 

      foo.Click += routedEventHandler; 

      grid.Children.Add(foo); 
     } 
    } 
+0

嘿Anurag UniformGrid缺少指令?有沒有這個命名空間? – 2012-03-24 02:44:13

+0

您也可以使用網格。我只是碰巧與UniformGrid玩耍。它在System.Windows.Controls.Primitives – 2012-03-24 02:45:40

+0

好吧它工作,但它現在填滿整個窗口? :( – 2012-03-24 02:53:41

1

什麼是您使用視框的推理?這是出於拉伸和比例原因嗎?

我建議使用一個畫布,然後你可以設置類似的Canvas.Left和Canvas.Top值如何設置XPOS和yPos。

然後,如果你想擁有視框的拉伸/縮放功能,你可以把你當成視框的孩子創建的畫布。

更新:爲了在運行時獲得畫布的ActualHeight和ActualWidth值,您可以爲SizeChanged添加一個事件處理程序(在XAML內輕鬆完成,但在代碼內不太難)來處理期間高度/寬度值的更改運行。下面的代碼解決方案:

bool initialized = false; // Should be located in class definition for your window 
          // ex. within "public partial class WindowName : Window 
canvas.SizeChanged += new SizeChangedEventHandler(canvas_SizeChanged); 
          // Can be located in constructor for window 
          // ie. public MainWindow() { /* put it right here */ } 

然後事件處理程序的定義可以如下:(此只創建一個按鈕,但會與你合作的for循環)

位置更新下面這個定義可以位於窗口的類def中,但低於布爾變量「initialized」的定義。 (前瓦特/「公共部分類WindowName:窗口」)

 private void canvas_SizeChanged(object sender, SizeChangedEventArgs e) 
      { 
      if (initialized == false) // so this only happens once. 
      { 
       int sizeValue = 100; 
       Random ranNum = new Random(); 
       int modHeight = System.Convert.ToInt32(canvas.ActualHeight)-sizeValue; 
       int modWidth = System.Convert.ToInt32(canvas.ActualWidth)-sizeValue; 
       Button foo = new Button(); 
       canvas.Children.Add(foo); 
       foo.Width = sizeValue; 
       foo.Height = sizeValue; 
       xPos = ranNum.Next(239) % modWidth; 
       yPos = ranNum.Next(307) % modHeight 
       Canvas.SetLeft(foo, xPos); 
       Canvas.SetTop(foo, yPos); 
       initialized = true; 
      } 
} 

或者,如果你知道你的畫布會多麼大小你可以手動設置modHeight和配置ModWidth到您所選擇的像素值而不必處理事件處理程序。

+0

啊啊啊!是的,這是由於這些原因viewbox isnt重要 – 2012-03-23 19:30:48

+0

事情是foo是一個按鈕xpos和ypos只對y,x位置的窗口作出反應我不能將它們包含在畫布內? – 2012-03-23 19:47:24

+0

'double canvasWidth = canvas1.Height; double canvasHeight = canvas1.Width; xPos = ranNum.Next(200)%canvasWidth; yPos = ranNum.Next(250)%canvasHeight;'如果我嘗試這個沒有任何反應依然停留在剛剛更新我的回答同一個地方 – 2012-03-23 20:16:21