我发现自己需要为我在一个程序中使用的几个 ToggleButton 元素定义一些样式和模板。我一切正常,除了我设置为内容的任何内容都没有显示。我不知道如何让我的内容正确显示。我的代码如下:
private Style m_ToggleStyle;
private Style ToggleStyle
{
get
{
if (m_ToggleStyle == null)
{
lock (new object())
{
if (m_ToggleStyle == null)
{
m_ToggleStyle = new Style(typeof(ToggleButton));
m_ToggleStyle.Setters.Add(new Setter { Property = ToggleButton.TemplateProperty, Value = ToggleTemplate });
}
}
}
return m_ToggleStyle;
}
}
private ControlTemplate m_ToggleTemplate;
private ControlTemplate ToggleTemplate
{
get
{
if (m_ToggleTemplate == null)
{
lock (new object())
{
if (m_ToggleTemplate == null)
{
m_ToggleTemplate = new ControlTemplate();
FrameworkElementFactory g = new FrameworkElementFactory(typeof(Grid));
g.SetValue(Grid.MarginProperty, new Thickness(0));
g.Name = "MainGrid";
FrameworkElementFactory cp = new FrameworkElementFactory(typeof(ContentPresenter));
cp.SetValue(ContentPresenter.NameProperty, "Contents");
cp.SetValue(ContentPresenter.HorizontalAlignmentProperty, System.Windows.HorizontalAlignment.Stretch);
cp.SetValue(ContentPresenter.VerticalAlignmentProperty, System.Windows.VerticalAlignment.Stretch);
cp.SetValue(ContentPresenter.MarginProperty, new Thickness(2));
cp.Name = "Contents";
g.AppendChild(cp);
m_ToggleTemplate.VisualTree = g;
ImageBrush ibBackgroundUnselected = new ImageBrush();
ibBackgroundUnselected.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Controls;component/Resources/TabUnselected.png", UriKind.Absolute));
g.SetValue(Grid.BackgroundProperty, ibBackgroundUnselected);
ImageBrush ibBackgroundSelected = new ImageBrush();
ibBackgroundSelected.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Controls;component/Resources/TabSelected.png", UriKind.Absolute));
Trigger tIsChecked = new Trigger { Property = ToggleButton.IsCheckedProperty, Value = true };
tIsChecked.Setters.Add(new Setter(Grid.BackgroundProperty, ibBackgroundSelected, "MainGrid"));
m_ToggleTemplate.Triggers.Add(tIsChecked);
}
}
}
return m_ToggleTemplate;
}
}
这在我动态创建 ToggleButtons 时使用,例如:
ToggleButton tbExample = new ToggleButton();
tbExample.Style = ToggleStyle;
tbExample.Content = "Content";