我發現自己需要定義一些樣式和模板,用於我在我的程序中使用的幾個ToggleButton元素。我有一切工作,除了我設定的內容不顯示。我對如何讓內容正確顯示感到不知所措。我的代碼如下:內容不顯示在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";
我也很好奇你爲什麼鎖定在你的兩個屬性訪問器中的新對象。那完成了什麼? – Charlie 2011-06-15 23:12:02
對不起,我對我的代碼進行了清理,從中刪除了一些可識別的內容,這是對它的快速修復。從我所瞭解的實際工作中,但我從來沒有在實踐中嘗試過,因爲擔心它不會。 – 2011-06-16 14:43:19