Answer the question
In order to leave comments, you need to log in
Is there an analogue of the "ItemsControl" element, but for a single element?
Let's say I have a phone class with its cost:
public class Phone
{
public int Price { get; set; }
pulic Phone(int price)
{
Price = price;
}
}
public class Xiaomi : Phone { public Xiaomi(int price) : base(price) { }}
public class IPhone : Phone { public IPhone(int price) : base(price) { }}
public ObservableCollection<Phone> Phones{ get => _Phones; set => _Phones= value; }
private ObservableCollection<Phone> _Phones = new();
<ItemsControl ItemsSource="{Binding Phones}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type Xiaomi}">
<TextBlock Text="Этот телефон Xiaomi стоит:"/>
<TextBlock Text="{Binding Path=Price}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type IPhone}">
<TextBlock Text="Этот телефон IPhone стоит:"/>
<TextBlock Text="{Binding Path=Price}"/>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
public Phone Telephone { get => _Telephone; set => _Telephone; }
private Phone _Telephone = new Xiaomi();
ContentControl
, but they didn’t explain exactly how, and there is no information on the Internet.
Answer the question
In order to leave comments, you need to log in
So, I found a normal solution. No crutches, no inefficient code. I knew there was an elegant solution. I'll post the old solution in the comments, because it's a pity the time wasted writing it.
To display a class object from the ViewModel, depending on its type, the element is used ContentPresenter
. In xaml its usage looks something like this:
<ContentPresenter Content="{Binding Telephone}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type cl:Xiaomi}">
<Label Content="Это ксяоми!"/>
</DataTemplate>
<DataTemplate DataType="{x:Type cl:IPhone}">
<Label Content="Ну а это не очень телефон такой..."/>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
ElementControl
, I don’t even know why.
A collection of one element will display one element.
However, you can just create a separate variable
https://metanit.com/sharp/wpf/11.php
<StackPanel>
<TextBlock Text="Этот телефон Xiaomi стоит:"/>
<TextBlock Text="{Binding XiomiPrice}"/>
</StackPanel>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question