A binding for generic objects in a specific scenario #20421
Replies: 3 comments 4 replies
-
|
Maybe you can implement a non generic interface to use here? |
Beta Was this translation helpful? Give feedback.
-
|
This is because WPF uses reflection to resolve bindings. You could instead use You can't bind to open generics, especially in this way. You're binding to a |
Beta Was this translation helpful? Give feedback.
-
|
You can sort of do this with DataTemplates. You'll need to make specific DataTemplates for each datatype, which can get messy, but does work unless you intend the generic to be unbounded. Looks a little like this, although I haven't worried about making sure the namespaces are correct, nor the exact syntax for the System types Int/Byte[]. This should give you an idea of how to make it work though. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a generic subclass that contains a generic property, and this class inherits from a base class. When I try to build a binding source, due to the generic nature of its subclass, I can only construct a collection of its base class. code like this:
public abstract class BaseClass : INotifyPropertyChanged { public event PropertyChangedEventHandler? PropertyChanged; private DataType dataType; //i8、i32、i64、byte[] [BsonId(autoId: true)] public int Id { get; init; } }public class SubClass : BaseClass { private T reVal; [BsonIgnore] public T ReVal { get { return reVal; } set { SetProperty(ref reVal,value); } } }Next, my ViewModel is implemented like this:
public partial class MainWindowViewModel : ObservableObject {
[ObservableProperty] private ObservableCollection baseObjects = [];
public MainWindowViewModel() {
BaseClass i32Object = new SubClass() {
Tag = $"Int Eob{i}"
};
i32Object .SetDataType(DataType.I32);
BaseObjects .Add(i32Object );
BaseClass blobObject= new SubClass<byte[]>() {
Tag = "Blob Eob"
};
blobObject.SetDataType(DataType.Blob);
BaseObjects .Add(blobObject);
}
}
In WPF, I can bind like this, and it works very well.
<ListBox ItemsSource="{Binding BaseObjects }"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <StackPanel.Resources> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="8,4" /> </Style> </StackPanel.Resources> <TextBlock Text="{Binding Tag}" /> <TextBlock Text="{Binding DataType}" /> <TextBlock Text="{Binding HoldBytes}" /> <TextBlock Text="{Binding ReVal, Converter={StaticResource ByteArrayToHexStringConverter}}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>But for the generic property
ReValin the subclass, if the listbox is directly bound toBaseObjects, it cannot recognize theReValproperty of its subclass. Is there any way to bind to the subclass property?Beta Was this translation helpful? Give feedback.
All reactions