开发者

How to use a specified variable in XAML in a C# file?

开发者 https://www.devze.com 2023-01-26 11:42 出处:网络
I am new to WPF. I would like to use the collection of Foods in my C# file, but I cannot seem to use FoodCategory as the variable. I wanted to access them as if they were in a list. So like Console.Wr

I am new to WPF. I would like to use the collection of Foods in my C# file, but I cannot seem to use FoodCategory as the variable. I wanted to access them as if they were in a list. So like Console.WriteLine(FoodCategory[0].Name);

How do I get FoodCategory in my C# file?开发者_如何学编程

 <Window.Resources>
        <src:FoodCollection x:Key="FoodCategory">
            <src:Food Name="Popcorn" 
                       ImagePath="Resources\popcorn.png"
                      />
            <src:Food Name="Drinks" 
                       ImagePath="Resources\drinks.png"
                      />
            <src:Food Name="Snacks"
                       ImagePath="Resources\snacks.png"
                       />
            <src:Food Name="Combo"
                       ImagePath="Resources\combo.png"
                       />
            <src:Food Name="Special"
                       ImagePath="Resources\nachos.png"
                       />
        </src:FoodCollection>

        <DataTemplate DataType="{x:Type src:Food}">
            <StackPanel Orientation="Vertical" Margin="0" Background="Transparent" Width="Auto">
                <Image Margin="10,0,10,0" Source="{Binding ImagePath}" Stretch="Fill" Width="120"/>
            </StackPanel>
        </DataTemplate>

    </Window.Resources>


The Window (actually, the System.Windows.FrameworkElement) has a FindResource method with which you can look up the resource based on its key.

See the MSDN article for details.


FindResource("FoodCategory")

should yield the resource. However, this certainly still needs a cast before being usable.

0

精彩评论

暂无评论...
验证码 换一张
取 消