2012-07-22 33 views
1

我需要使用c#代碼爲xaml標記中的多邊形生成動態點而不是靜態點來創建此樣式。如何在C#代碼中創建樣式並將其傳遞給WPF中的xaml for windows?

<Style x:Key="Mystyle" TargetType="Button"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type Button}"> 
        <Grid > 

          <Polygon Points="0,0 0,100 50,200" Fill="{TemplateBinding Background}" 
         Stroke="{TemplateBinding BorderBrush}" DataContext="{Binding}" /> 
         <ContentPresenter HorizontalAlignment="Center" 
             VerticalAlignment="Center"/> 
        </Grid> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
+3

你真正問的是如何在代碼中創建控件模板,因爲所有的風格確實是分配的模板。也許你應該改變你的問題的標題。 – 2012-07-22 00:38:11

回答

4
public MainWindow() 
    { 
     //Control Template .. We cannot add children to the Control Template Directly 

     ControlTemplate controlTemplate = new ControlTemplate(typeof(Button)); 

     //These points you can set Dynamically as your requirement 
     PointCollection points= new PointCollection(new List<Point> { new Point() { X = 0, Y = 0 }, new Point() { X = 0, Y = 50 }, new Point() { X = 100, Y = 200 } }); 
     var polygon = new FrameworkElementFactory(typeof(Polygon)); 

     //You can also set Binding rather than static color for fill 
     polygon.SetValue(Polygon.PointsProperty, points); 
     polygon.SetValue(Polygon.FillProperty, new SolidColorBrush(Colors.Pink)); 

     //ContentPresenter 
     var contentPresenter = new FrameworkElementFactory(typeof(ContentPresenter)); 
     contentPresenter.SetValue(ContentPresenter.ContentProperty,"this is content Presenter"); 

     //Grid 
     var grid = new FrameworkElementFactory(typeof(Grid)); 
     grid.SetValue(Grid.BackgroundProperty, new SolidColorBrush(Colors.Yellow)); 
     grid.AppendChild(polygon); 
     grid.AppendChild(contentPresenter); 
     controlTemplate.VisualTree = grid; 

     //Style 
     Style style = new Style(typeof(Button)); 
     style.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Red))); 
     style.Setters.Add(new Setter(TemplateProperty, controlTemplate)); 
     this.Resources.Add("SomeKey", style); 

     //Initialize 
     InitializeComponent(); 
    } 

<Grid> 
    <Button Style="{DynamicResource SomeKey}"/> 
</Grid> 

我希望這會幫助你給出想法該怎麼做。是的,你可以在後面的代碼中設置所有綁定,如多邊形的填充和ContentPresenter的內容。

注意建議使用Xaml創建模板。就像你的問題一樣,你想要的只是多邊形的動態點。它更好地綁定Polygon的Points屬性,而不是在CodeBehind中創建整個Template。

0

而是在代碼中創建的風格,我會建議你有property in your class and bind your points dependency property with that property如果你不想在XAML到預先定義的點做。這就是Binding派上用場的地方。

+0

我被這個建議很感興趣 - 你能在與一些示例代碼擴展? – jbyrd 2017-11-02 13:53:28

相關問題