Can I bind a WPF control to a field property?

Since I needed to share some functionality between classes, I came to the following situation

xaml code

<CheckBox IsChecked="{Binding MyObjectField.MyBoolean}" /> 

view model

 ... public MyInternalObject MyObjectField; ... 

Class myobject

 public class MyInternalObject { ... public bool MyBoolean { get; set; } ... } 

This does not work unless I replicate the MyBoolean property in the View Model class.

 public bool MyBoolean { get { return MyInternalObject.MyBoolean; } set { MyInternalObject.MyBoolean=value; } } 

Does anyone have any ideas?

+6
source share
3 answers

No, you can’t. Because the binding system uses Reflection to search

Property in a DataContext (i.e. your virtual machine)

He is not looking for a field. Hope this helps.

+4
source

You cannot yet ( in WPF version 4.5 you can bind to a static property ). But you can create your property in App.xaml.cs

 public partial class App : Application { public bool MyBoolean { get; set; } } 

and bind everywhere.

 <CheckBox IsChecked="{Binding MyBoolean, Source={x:Static Application.Current}}"> 
+5
source

Instead of binding the element to the field property, I changed the DataContext of the element to the desired field.

  protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); MainWindowView mainWindowView = new MainWindowView(); var mainWindowViewModel = new MainWindowViewModel(); mainWindowView.DataContext = mainWindowViewModel; mainWindowView.pagerView.DataContext = mainWindowViewModel.pager; mainWindowView.Show(); } 

In this example, I have a DataGrid and Pager (first, previous, next, last page) below. MainWindowView elements (including DataGrid) are bound to properties in MainWindowViewModel, but pager buttons are bound to mainWindowViewModel.pager properties.

MainWindowView:

  <DataGrid Name="dgSimple" ItemsSource="{Binding DisplayedUsers}" MaxWidth="200" Grid.Row="0" SelectedItem="{Binding SelectedRow}"></DataGrid> <view:PagerView x:Name="pagerView" Grid.Row="2"/> 

PagerView:

 <UserControl x:Class="wpf_scroll.View.PagerView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:wpf_scroll.View" mc:Ignorable="d" d:DesignHeight="30" d:DesignWidth="350"> <StackPanel Orientation="Horizontal" Grid.Row="1"> <Label Content="Page size:"/> <TextBox Text="{Binding PageSize}" Width="30" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></TextBox> <Button Content="First" Command="{Binding FirstPageCommand}"></Button> 
0
source

Source: https://habr.com/ru/post/921229/


All Articles