我为尝试将以下代码转换为纯C#而感到困惑。此XAML代码来自Cavanaghs博客,内容涉及如何在任何东西上打圆角。该代码有效,但是我需要将其转换为c#,因为在某些情况下我需要它是动态的。如果您能帮助的话,那将很棒。
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType='{x:Type ListViewItem}'>
<Grid>
<Border CornerRadius="15" Name="mask" Background="White"/>
<StackPanel Background="Beige">
<StackPanel.OpacityMask>
<VisualBrush Visual="{Binding ElementName=mask}"/>
</StackPanel.OpacityMask>
<GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}"/>
<TextBlock Background="LightBlue" Text="{Binding News}" />
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
到目前为止,我有以下内容,但出现错误。
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,则由于其FrameworkElementFactory而无法将边框作为Visual传递。
只是我迷路了,任何帮助将不胜感激。
谢谢你的帮助
最佳答案
您不想知道这一点。说真的,你不做,这是一场噩梦。
编辑:如果我没有犯任何错误,这是您的代码的翻译...
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;
编辑:仍然存在一个错误,不能这样创建
VisualBrush
,其余的似乎可以正常工作。