2009-06-03 91 views
6

如何強制WPF中的ToolController中的UserControl使用ToolBar的默認按鈕樣式?使ToolBar按鈕樣式適用於工具欄中的UserControls

我有具有XAML是這樣叫的ImageButton一個簡單的用戶控件:

<UserControl x:Class="myNameSpace.ImageButtonUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Name="imageButton" 
    > 
    <Button Style="{Binding ElementName=imageButton, Path=ButtonStyle}"> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="{Binding ElementName=imageButton, Path=ImageSource}" 
        VerticalAlignment="Center" 
        /> 
      <TextBlock Text="{Binding ElementName=imageButton, Path=Text}" 
         Style="{Binding ElementName=imageButton, Path=TextStyle}" 
         VerticalAlignment="Center" 
         /> 
     </StackPanel> 
    </Button> 
</UserControl> 

我有一些依賴屬性後面的代碼對那些結合的路徑,一切工作正常。

直到我把它放在ToolBar中。通常,當你將按鈕放在ToolBar中時,它們會被ToolBar重新設置爲看起來像工具欄按鈕。我已經發現如何改變這種風格(請參閱ToolBar.ButtonStyleKey。但是我怎樣才能將已定義的風格應用到我的用戶控件的按鈕樣式依賴項屬性?

回答

19

哦,我的道歉!我誤解了你的問題。給這個鏡頭:

<Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"> 
    Hello, world! 
</Button> 

風格只針對按鈕,所以它只能應用於按鈕。 (這不會是你的評論的外觀問題。)

0

你需要一些強大的黑魔法才能使它爲你的usercontrol自動創建一個功能正常的新樣式,每種類型的內置控件都有內置樣式,你可以添加到工具欄中(注意ToolBar.ButtonStyleKey不是單獨的)。你需要製作和運用你自己的風格,自己相匹配的標準工具欄元素。

+0

我不想自動創建一個,我只想將現有的按鈕樣式應用到我的UserControl中的按鈕。 – Ray 2009-06-03 23:00:34

4

我找到了一種方法,似乎工作,但我感興趣的是解決這個的其他方式。

我添加了一個加載的事件處理程序到我的UserControl並把它放在裏面。

if (button.Style == null && this.Parent is ToolBar) 
{ 
    button.Style = (Style)FindResource(ToolBar.ButtonStyleKey); 
} 

其中button是我的UserControl中按鈕的名稱。