【问题标题】:Problem setting Icon image source in Context Menu from code behind从后面的代码在上下文菜单中设置图标图像源的问题
【发布时间】:2012-04-04 01:15:20
【问题描述】:

我在 UserControl 中有一个 DataGrid,并且我在 DataGrid 中添加了一个 ContextMenu。

XAML 如下:

<sdk:DataGrid ItemsSource="{Binding Path=GridSource}">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding Path=Name, Mode=OneWay}" Header="Name"/>
        <sdk:DataGridTextColumn Binding="{Binding Path=Number, Mode=OneWay}" Header="Number"/>
    </sdk:DataGrid.Columns>
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu Opened="ContextMenu_Opened">
            <toolkit:MenuItem IsEnabled="False">
                <toolkit:MenuItem.Icon>
                    <Image x:Name="menuIcon"/> 
                </toolkit:MenuItem.Icon>
            </toolkit:MenuItem>
            <toolkit:Separator />
            <toolkit:MenuItem Header="View Agent Route" Click="AgentRoute_Click"/>
            <toolkit:MenuItem Header="Live Track" Click="LiveTrack_Click"/>
        </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</sdk:DataGrid>

如果我使用 XAML 设置 menuIcon Image 的来源

<Image x:Name="menuIcon" Source="../../Assets/Images/user_green.png"/>

然后图标渲染得很好,但如果我尝试在 ContextMenu_Opened 事件处理程序中使用:

private void ContextMenu_Opened(object sender, RoutedEventArgs e)
{
  menuIcon.Source = new BitmapImage(new Uri("../../Assets/Images/user_green.png", UriKind.Relative));
}

什么都没有显示,我没有收到错误或任何它没有显示的内容。我已经使用相同的方法在我的应用程序的其他地方设置了 ImageSource(使用相同的实际 *.png 文件),有什么想法吗?

这是因为它是 ContextMenu 吗?在网格上?我不知道发生了什么。

【问题讨论】:

    标签: silverlight image silverlight-4.0 contextmenu


    【解决方案1】:

    尝试使用:-

     new Uri("/Assets/Images/user_green.png", UriKind.Relative")
    

    作为一般规则,如果可能的话,我会避免使用“..”父路径,它们只会让人头疼。你知道 Xap 的根目录有一个 Assets 文件夹,所以从“/Assets”开始并从那里开始。

    【讨论】:

    • 试过了,但还是不行。你能想到为什么它在通过 XAML 设置而不是通过后面的代码设置时起作用的任何原因吗?
    【解决方案2】:

    我通过在 contextmenu_opened 事件中使用 ImageSourceConverter 使这个工作正常。

    private void ContextMenu_Opened(object sender, RoutedEventArgs e)
    {
      ImageSourceConverter converter = new ImageSourceConverter();
      menuIcon.Source = (ImageSource)converter.ConvertFromString("../../Assets/Images/user_green.png");
    }
    

    【讨论】:

      【解决方案3】:

      你必须传入一个图像。这对我有用:

      var mus = new MenuItem {
      Header = "Unicorns...",
      Icon = new Image {
       Source = new BitmapImage(new Uri("/myApp;component/img/unicorns.png",UriKind.Relative))
      }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-25
        • 2012-08-20
        • 1970-01-01
        • 2011-04-11
        相关资源
        最近更新 更多