2012-04-19 140 views
-1

請解釋爲什麼不到風度工作..WPF文本菜單綁定菜單項的圖標到菜單項頭

<ContextMenu>  
     <MenuItem> 
      <MenuItem.Header> 
       <TextBox Name="tbColor" Text="Black" /> 
      </MenuItem.Header> 
      <MenuItem.Icon> 
       <TextBox Text="{Binding ElementName=tbColor,Path=Text}" /> 
      </MenuItem.Icon>                  
     </MenuItem> 
</ContextMenu> 

我嘗試了好幾種方法,但一無所獲。 RelativeSource不工作..

編輯..從另一個控制工程結合..

<DataGrid Foreground="{Binding ElementName=tbColor,Path=Text,Converter={StaticResource textToBrushConverter}}">   
     <DataGrid.ContextMenu> 
      <ContextMenu>....    
+3

爲什麼你認爲你可以添加一個'TextBox'到一個需要'Image'的屬性? – slugster 2012-04-19 12:47:47

+0

我不希望有圖像。你可以放置你想要的任何控制。在原始代碼中,根據您使用轉換器在標題文本框中輸入的內容,將會有一個矩形更改顏色。 – jrb 2012-04-19 12:52:03

回答

1

得到了原代碼的工作這樣的..醜,但我自己的理智..

<MenuItem.Header> 
    <TextBox Name="tbColor" Text="Black" TextChanged="tbColor_TextChanged" /> 
</MenuItem.Header> 
<MenuItem.Icon> 
    <Rectangle Name="rectangleColor" Width="20" Height="20" /> 
</MenuItem.Icon> 

而且在後面的代碼..

private void tbColor_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     try 
     { 
      rectangleColor.Fill = new SolidColorBrush((Color) ColorConverter.ConvertFromString(((TextBox) sender).Text)); 
     } 
     catch (Exception) 
     { 
      return; 
     } 
    } 
3

就讓我們來看看通過MSDNContextMenuMenuItemHeaderedItemsControl使它看起來像你可以把你想要的任何東西在MenuItemHeader。更仔細的檢查表明情況並非如此。 MenuItemHeader屬性實際上是查找字符串。您可以在Header內放置TextBlock,但不能放入TextBox

雖然我沒有深入研究過,但我懷疑MenuItem對象的Icon屬性是一樣的(除了圖片)。

+0

我可以明確地設置我想在標題中的任何控件。我也可以通過contextMenu之外的控件綁定到texbox。 – jrb 2012-04-19 13:56:19

0

您的控件的可視化樹之外的上下文菜單無法找到元素名稱。 嘗試 -

{結合PlacementTarget,的RelativeSource = {的RelativeSource FindAncestor, AncestorType = {X:類型文本菜單}}}」

+1

之前嘗試過不同的變化,但我沒有工作。你也不應該能夠在同一個控件中綁定。 – jrb 2012-04-19 13:58:13