2017-04-04 153 views
0

不知道這是否是「最好」的方式來做到這一點。 我正在學習MVVM的概念,對此深表歉意。MVVM VisualBrush綁定

我有4個按鈕,我想在一個矩形內顯​​示一個VisualBrush。 這裏是我的代碼:

查看:

<Controls:MetroWindow.RightWindowCommands> 
    <Controls:WindowCommands Name="WindowCommand" ItemsSource="{Binding Model.WindowCommandItems}"> 
     <Controls:WindowCommands.ItemTemplate> 
      <DataTemplate DataType="{x:Type ModelType:MainModel}"> 
       <Button Command="{Binding Command}"> 
        <StackPanel Orientation="Horizontal"> 
         <Rectangle Width="20" 
          Height="20"> 
          <Rectangle.OpacityMask> 
           <VisualBrush Stretch="Fill" Visual="{Binding Icon}" /> 
          </Rectangle.OpacityMask> 
         </Rectangle> 
         <TextBlock Margin="4 0 0 0" 
          VerticalAlignment="Center" 
          Text="{Binding Header}" /> 
        </StackPanel> 
       </Button> 
      </DataTemplate> 
     </Controls:WindowCommands.ItemTemplate> 
    </Controls:WindowCommands> 
</Controls:MetroWindow.RightWindowCommands> 

視圖模型:

private void CreateWindowCommands() { 
     var myResourceDictionary = new ResourceDictionary(); 
     myResourceDictionary.Source = 
      new Uri("/BlackBoxBot;component/Resources/Icons.xaml", 
        UriKind.RelativeOrAbsolute); 

     Model.WindowCommandItems = new ObservableCollection<Models.MainModel.WindowCommandModel> { 
      new Models.MainModel.WindowCommandModel { 
       Header = "Viewer", 
       Icon = new VisualBrush() { Visual = (Visual)myResourceDictionary["users"] as Canvas} 
      }, 
      new Models.MainModel.WindowCommandModel { 
       Header = "Home", 
       Icon = new VisualBrush() { Visual = (Visual)myResourceDictionary["appbar_home"] as Canvas } 
      }, 
      new Models.MainModel.WindowCommandModel { 
       Header = "Dashboard", 
       Icon = new VisualBrush() { Visual = (Visual)myResourceDictionary["theater"] as Canvas } 
      }, 
      new Models.MainModel.WindowCommandModel { 
       Header = "Einstellungen", 
       Icon = new VisualBrush() { Visual = (Visual)myResourceDictionary["settings"] as Canvas } 
      } 
     }; 
    ...... 

型號:

[PropertyChanged.ImplementPropertyChanged] 
    public class WindowCommandModel { 
     public string Header { get; set; } 
     public ICommand Command { get; set; } = new RoutedCommand(); 
     public VisualBrush Icon { get; set; } 
    } 

我的結果:

Result

爲什麼我的圖標不顯示?

回答

1
<VisualBrush Stretch="Fill" Visual="{Binding Icon}" /> 

VisualBrush.Visual期望對象爲類型Visual

要綁定到一個VisualBrush

Icon = new VisualBrush() { Visual = (Visual)myResourceDictionary["users"] as Canvas} 

試試這個:

Icon = myResourceDictionary["users"] as Canvas