【发布时间】:2015-06-10 19:18:10
【问题描述】:
尝试再次解决这个问题,(来自以前的帖子,但我有几个问题需要解决)。
这里的目标是使用在 XAML 中创建的模板从头开始生成多个按钮。每个按钮都是一个带有“简单图标”(PNG /w Alpha)的圆圈,并通过悬停改变颜色。我遇到的问题是在生成图像时让每个按钮更改图像。我似乎无法从 XAML 访问 x:Key 变量。它现在可以渲染默认模板(图像和颜色工作)。当我尝试将图像更改为我想要显示的新“图标”时,我似乎无法引用 x:Keys (cBG, cBGHi, id, idHi)。
这是我的代码,以及之后的一些注释。提前致谢! :)
XAML
<SolidColorBrush x:Key="cBG" Color="#FFFFFF"/>
<SolidColorBrush x:Key="cBGHi" Color="#00AAFF"/>
<ImageSource x:Key="id">D:\32start.png</ImageSource>
<ImageSource x:Key="idHi">D:\32startHi.png</ImageSource>
<Style x:Key="UXButton" TargetType="{x:Type Button}">
<Setter Property ="Template">
<Setter.Value>
<ControlTemplate x:Name ="userControl" TargetType ="{x:Type Button}">
<Grid x:Name="Grid">
<Ellipse Name ="bgg" Fill="{StaticResource cBG}" Margin="4"/>
<Image x:Name="UXImage" Width="32" Height="32" Source="{DynamicResource id}">
<Image.Clip>
<EllipseGeometry Center="16,16" RadiusX="16" RadiusY="16"/>
</Image.Clip>
</Image>
<ContentPresenter HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property ="IsMouseOver" Value ="True">
<Setter TargetName ="bgg" Property ="Fill" Value ="{StaticResource cBGHi}"/>
<Setter TargetName ="UXImage" Property="Source" Value="{DynamicResource idHi}"/>
</Trigger>
<Trigger Property ="IsPressed" Value ="True">
<Setter TargetName ="bgg" Property ="Fill" Value ="{StaticResource cBG}"/>
<Setter TargetName ="UXImage" Property="Source" Value="{DynamicResource id}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
C#.cs
private void BuildStack()
{
Button b;
Style UXStyle = (Style)FindResource("UXButton");
// UXStyle.id = new BitmapImage(new Uri("D:\NewImage1.png", UriKind.Relative));
// UXStyle.idHi = new BitmapImage(new Uri("D:\NewImage2.png", UriKind.Relative));
b = new Button();
b.Style = UXStyle;
b.HorizontalAlignment = HorizontalAlignment.Left;
b.VerticalAlignment = VerticalAlignment.Top;
b.Margin = new Thickness(10, 10, 0, 0);
b.Width = 48;
b.Height = 48;
UX.Children.Add(b);
}
//注意事项
- XAML 位于名为“ButtonStyle.XAML”的 ResourceDictionary 中
- 模板在 XAML 中。 Button 是在 Code Behind 中生成的。
- 我可以并且有在整个程序中使用的 preRender 按钮,但是这部分是特殊的,因为它是“最近”或“最喜欢的文件”之类的东西。使图标与字符串匹配的可能性将是巨大的。 (想想歌曲的专辑封面,或者快捷方式的开始菜单图标)。
- 我已经在 Google 上上下搜索过了。要么,这是不可能的,要么我不知道命名法。
- 我确实找到了一个叫做 Binding 或 DataBinding 的东西,但我遇到了同样的问题(在 Code Behind 中访问它)。
- 再次感谢!
【问题讨论】:
-
我可能不得不回来实际阅读所有这些内容,但快速浏览一下我想知道为什么不将您的按钮设置为 ItemsControl 的 ItemTemplate 并通过依赖项属性中的值传递项目(在这种情况下是按钮)?
-
@ChrisW。当我试图找出 Binding 是如何工作的时,我已经把它写下来了。我通过示例学习得最好,但是缺少 MSDN。 :(
-
有点像this