How to reuse vector images in wpf properly

寵の児 提交于 2019-12-13 14:24:53

问题


X problem:

I want to use vector graphic in WPF.

I have bunch of SVG files, which I can convert into XAML by using Inkscape. Resulting xaml is ResourceDictionary with ViewBox / Canvas containing Path, etc. Dictionaries are merged into App.xaml and I can use key to access them.

Question: how to use such images? It looks like I am not using them properly.

Here is how I am using them

<Viewbox Child="{StaticResource MyImageResourceKey}" Width="100" Height="100"/>

But it looks like I can use it only once (in one place)! Attempting to use that image in multiple places simultaneously will either remove it from previous place or will throw

System.ArgumentException: Must disconnect specified child from current parent Visual before attaching to new parent Visual.

Y problem

I want to show a list of vector images. I display them like this

<ItemsControl ItemsSource="{Binding Images}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Viewbox Width="100" Height="100">
                <ContentPresenter Content="{Binding Image}"/>
            </Viewbox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl> 

ViewModel

public class ViewModelSomeWindow : INotifyPropertyChanged
{
    public class MyImage
    {
        public object Image { get; set; }
    }

    private ObservableCollection<MyImage> _images;
    public ObservableCollection<MyImage> Images
    {
        get { return _images; }
        set { _images = value; OnPropertyChanged(); }
    }
    ...
}

And items are added like this

Images.Add(new MyImage() { Image = App.Current.Resources["MyImageResourceKey"] });

Problem: when using same image ("MyImageResourceKey") for second item, then first item displays (blank) image. If image is already displayed with the use of StaticResource somewhere, then adding item will throw above ArgumentException.

P.S.: I need to solve Y problem, but perhaps I am not using vector graphic properly.


回答1:


Please Use x:shared =false in path as shown in attached image

and visit this link too for reference



来源:https://stackoverflow.com/questions/27172730/how-to-reuse-vector-images-in-wpf-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!