MenuItem.Header和MenuItem.Icon DataTemplate

时间:2017-12-30 20:36:36

标签: wpf xaml menu menuitem

我有一个包含以下两个菜单项的菜单:

<MenuItem Header="Item1">
  <MenuItem.Icon>
    <cc:Icon ImageSource="..." Size="22"/>
  </MenuItem.Icon>
</MenuItem>
<MenuItem Header="Item2">
  <MenuItem.Icon>
    <cc:Icon ImageSource="..." Size="22"/>
  </MenuItem.Icon>
</MenuItem>

正如您所看到的,每个Item都有一个名称为&#34; Header&#34;和一个Icon(我自己的控件)作为&#34; Icon&#34;。

我没有在XAML中明确地编写它们,而是想将ItemsSource绑定到ViewModel中的List<MenuItem>对象,如下所示:

ItemsSource="{Binding Path=SomeMenu}"

我的MenuItem类有字段&#34;字符串名称&#34;和ImageSource Icon我想绑定到标题和我的菜单项Icon部分完全我在这里做了什么。

我认为正确的方法是使用DataTemplate,如下所示:

<Menu.ItemTemplate>
  <DataTemplate>
    <!-- TODO: Bind the Header and Icon properties-->
    <TextBlock Text="{Binding Path=Name}"/>
    <!-- how to bind the icon? -->
  </DataTemplate>
<Menu.ItemTemplate>

但我不明白如何分别定义标题和Icon模板。

我如何做到这一点,而不是?

更新:我希望<cc:Icon>在menuItem模板中显示为<contentPresenter Source="Icon">textBox出现时<contentPresenter Source="Header">出现@Cacheable(value = "apis", key = "#request") public Object queryCenterAPI(QCRequest request,HttpHeaders headers) throws JSONException, ParseException { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new ToolsResponseHandler()); Response res=new Response(); HashMap<String,String> map=new HashMap<String,String>(); logger.info("No Caching^^^^^^^^^^"); Gson gson = new Gson(); String requestJson = gson.toJson(request); HttpEntity<String> requestEntity = new HttpEntity<String>(requestJson, headers); System.out.println("Request Body "+requestEntity); Object response = null; try { response = restTemplate.postForObject(QCUtils.queryURL, requestEntity, Object.class); logger.info("1st response>"+response); response = response.toString().replaceAll("\\\\", ""); System.out.println("Final response "+response); }catch (HttpClientErrorException httpEx) { logger.info("Error:"+httpEx); } return response; } @CacheEvict(value = "apis", key = "#request") public void resetOnRequest(QCRequest request) { // Intentionally blank System.out.println("Evict in Progrsss......"); } 1}}

1 个答案:

答案 0 :(得分:1)

我相信这就是你想要的:

<Menu ItemsSource="{Binding SomeMenu}">
        <Menu.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Icon">
                    <Setter.Value>
                        <cc:Icon Source="{Binding Icon}"></Image>
                    </Setter.Value>
                </Setter>
                <Setter Property="Header" Value="{Binding Name}"/>
            </Style>
        </Menu.ItemContainerStyle>    
</Menu>

还是我再次悲惨地失败了? :)