How to setup a Style with Bindings in Code-Behind #19763
Replies: 2 comments
-
|
I’m not sure what kind of conversion you performed in Assuming the conversion logic you implemented in Func<int, int> conversion = x => x;So, you can use C# in the code-behind to create a IValueConverter converter = new FuncValueConverter<int, int>(conversion);
Style style = new(x => x.OfType<ItemsControl>().Child().OfType<ContentPresenter>())
{
Setters =
{
new Setter(
Grid.ColumnProperty,
new Binding("Position.Column") { Converter = converter }
),
new Setter(
Grid.RowProperty,
new Binding("Position.Row") { Converter = converter }
),
}
};If you want to yield that converter, you can use compiled bindings to inline the conversion. Style style = new(x => x.OfType<ItemsControl>().Child().OfType<ContentPresenter>())
{
Setters =
{
new Setter(Grid.ColumnProperty, new CompiledBindingExtension(
new CompiledBindingPathBuilder()
.TypeCast<TileFormModel>()
.Property(
new ClrPropertyInfo(
nameof(TileFormModel.Position.Column),
obj => ((TileFormModel) obj).Position.Column,
(obj, val) => ((TileFormModel) obj).Position.Column = val is int v ? conversion(v) : 0,
typeof(int)),
PropertyInfoAccessorFactory.CreateInpcPropertyAccessor
).Build())),
new Setter(Grid.RowProperty, new CompiledBindingExtension(
new CompiledBindingPathBuilder()
.TypeCast<TileFormModel>()
.Property(
new ClrPropertyInfo(
nameof(TileFormModel.Position.Row),
obj => ((TileFormModel) obj).Position.Row,
(obj, val) => ((TileFormModel) obj).Position.Row = val is int v ? conversion(v) : 0,
typeof(int)),
PropertyInfoAccessorFactory.CreateInpcPropertyAccessor
).Build())),
}
};Finally, add the style into your YourItemsControl.Styles.Add(style); |
Beta Was this translation helpful? Give feedback.
-
|
Roger. I had everything there already, short of the Thanks for the input. |
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've got the following style for laying out ViewModel items within a Grid, and I'm curious if there's a way I could set this up in code-behind, so I could just do the conversions inline, instead of having to create two whole
IValueConverters.So far, I haven't had any other issues with doing proper bindings in code-behind, which I tend to prefer, as it's generally less verbose, and more type-safe.
Beta Was this translation helpful? Give feedback.
All reactions