如何在Uno Platform中通过C#创建Material Card并配置模板?
在Uno Platform中用C#创建Material Card
在Uno Platform的Material Card组件中,HeaderContentTemplate和SubHeaderContentTemplate需要通过DataTemplate定义内容的呈现逻辑,你可以直接在C#中创建这些模板并绑定到Card的对应属性。以下是完整实现示例:
基础实现代码
// 创建Card实例 Card myCard = new Card(); // 配置Header内容模板 myCard.HeaderContentTemplate = new DataTemplate(() => { var headerTextBlock = new TextBlock { // 使用Uno Material内置的标题样式 Style = (Style)Application.Current.Resources["MaterialCardHeaderTextBlockStyle"], Margin = new Thickness(16, 16, 16, 0) }; // 将HeaderContent绑定到TextBlock的Text属性 headerTextBlock.SetBinding( TextBlock.TextProperty, new Binding { Source = myCard, Path = new PropertyPath(nameof(Card.HeaderContent)) } ); return headerTextBlock; }); // 配置SubHeader内容模板 myCard.SubHeaderContentTemplate = new DataTemplate(() => { var subHeaderTextBlock = new TextBlock { // 使用Uno Material内置的子标题样式 Style = (Style)Application.Current.Resources["MaterialCardSubheaderTextBlockStyle"], Margin = new Thickness(16, 4, 16, 16) }; // 将SubHeaderContent绑定到TextBlock的Text属性 subHeaderTextBlock.SetBinding( TextBlock.TextProperty, new Binding { Source = myCard, Path = new PropertyPath(nameof(Card.SubHeaderContent)) } ); return subHeaderTextBlock; }); // 设置标题和子标题内容 myCard.HeaderContent = "test"; myCard.SubHeaderContent = "test"; // 将Card添加到Grid Grid.SetRow(myCard, k); Grid.SetColumn(myCard, l); myGrid.Children.Add(myCard);
自定义扩展示例(带图标标题)
如果需要更复杂的布局(比如标题旁添加图标),可以在DataTemplate中使用布局容器组合控件:
myCard.HeaderContentTemplate = new DataTemplate(() => { // 创建横向布局容器 var headerLayout = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(16, 16, 16, 0), Spacing = 8 // 控件间间距 }; // 添加图标控件 var headerIcon = new SymbolIcon { Symbol = Symbol.Info, Width = 24, Height = 24, Foreground = new SolidColorBrush(Colors.Gray) }; headerLayout.Children.Add(headerIcon); // 添加标题文本 var headerTextBlock = new TextBlock { Style = (Style)Application.Current.Resources["MaterialCardHeaderTextBlockStyle"] }; headerTextBlock.SetBinding( TextBlock.TextProperty, new Binding { Source = myCard, Path = new PropertyPath(nameof(Card.HeaderContent)) } ); headerLayout.Children.Add(headerTextBlock); return headerLayout; });
额外说明
- 若不需要使用内置的Material样式,可以直接修改TextBlock的
FontSize、Foreground、FontWeight等属性自定义外观。 - 模板中可以嵌套任意布局容器和控件,满足不同的UI需求。
内容的提问来源于stack exchange,提问作者Clinton Walsh
相关产品推荐
相关产品推荐

