将ControlTemplate XAML转换为C#

我一直难以尝试将以下代码转换为纯c#。 这个XAML代码来自Cavanaghs博客,关于如何在任何东西上制作圆角。 代码可以工作但我需要将它转换为c#,因为在某些情况下我需要它是动态的。 如果你能提供帮助那就太好了。

               

到目前为止,我有以下但我得到错误。

 FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border)); border.SetValue(Border.BackgroundProperty, Brushes.White); border.SetValue(Border.CornerRadiusProperty, new CornerRadius(8, 8, 8, 8)); border.SetValue(Border.NameProperty, "roundedMask"); 

据我所知,我不能将VisualBrush作为FrameworkElementFactory(崩溃),但如果我将它声明为常规元素VisualBrush,我不能将其作为VisualE传递边界,因为它是一个FrameworkElementFactory。

只是我迷路了,任何帮助将不胜感激。 谢谢你的帮助

你不想知道这个。 说真的,你没有,这是一场噩梦。

编辑:如果我没有犯任何错误,这是你的代码的翻译…

 Setter setter = new Setter(); setter.Property = ListViewItem.TemplateProperty; ControlTemplate template = new ControlTemplate(typeof(ListViewItem)); var grid = new FrameworkElementFactory(typeof(Grid)); var border = new FrameworkElementFactory(typeof(Border)); border.SetValue(Border.BackgroundProperty, Brushes.White); border.SetValue(Border.NameProperty, "mask"); border.SetValue(Border.CornerRadiusProperty, new CornerRadius(15)); grid.AppendChild(border); var stackPanel = new FrameworkElementFactory(typeof(StackPanel)); stackPanel.SetValue(StackPanel.BackgroundProperty, Brushes.Beige); var visualBrush = new FrameworkElementFactory(typeof(VisualBrush)); visualBrush.SetBinding(VisualBrush.VisualProperty, new Binding() { ElementName = "mask" }); stackPanel.SetValue(StackPanel.OpacityMaskProperty, visualBrush); var gridViewRowPresenter = new FrameworkElementFactory(typeof(GridViewRowPresenter)); gridViewRowPresenter.SetValue(GridViewRowPresenter.ContentProperty, new TemplateBindingExtension(GridViewRowPresenter.ContentProperty)); gridViewRowPresenter.SetValue(GridViewRowPresenter.ColumnsProperty, new TemplateBindingExtension(GridView.ColumnCollectionProperty)); stackPanel.AppendChild(gridViewRowPresenter); var textBlock = new FrameworkElementFactory(typeof(TextBlock)); textBlock.SetValue(TextBlock.BackgroundProperty, Brushes.LightBlue); textBlock.SetBinding(TextBlock.TextProperty, new Binding("News")); stackPanel.AppendChild(textBlock); grid.AppendChild(stackPanel); template.VisualTree = grid; setter.Value = template; 

编辑:还有一个bug, VisualBrush无法像这样创建,其余的似乎工作。

您实际上不必将其转换为C#以动态应用它。 如果将其添加到应用程序资源中,请在App.xaml文件中添加如下:

               

请注意键入此项目的x:Key属性。

然后,您可以在代码中的任何位置查找…

 ControlTemplate template = this.Findresource("MyListViewItemTemplate") as ControlTemplate 

然后,您可以在需要时应用它!