Fenix Devoper

Fenix Devoper

  • 1.6k
  • 2
  • 549

How to binding an object property in a userControl?

Jul 12 2023 12:26 PM

Hi, i'm having a rough fight with WPF and its Binding system. I just wanna bind a property of an instance called HPP, this property is pressure and this object exist in MainViewModel, so in MainWindow.xaml a have this:

<componentes:SetComponent x:Name="HPP_Trip_Route" Grid.Row="1" Grid.Column="1" VerticalAlignment="Top" Title="TRIP" VariableValue="{Binding HPPRoute.Pressure}" Unity="PSI" Loaded="SetComponent_Loaded" FSizeTitle="24" FSizeVariable="36" FSizeUnity="14"/>

In SetComponent:

<TextBlock x:Name="ValueSetComponent" Grid.Row="1" Text="{Binding VariableValue, RelativeSource={RelativeSource AncestorType=UserControl}}" FontSize="{Binding FSizeVariable}" HorizontalAlignment="Right" VerticalAlignment="Bottom" Foreground="#FFFFFF" Margin="0, 5, 0, 5 "/>

In MainWindow.xaml.cs:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private readonly Variables GV = Variables.GetInstancia();
    private MainViewModel _mainViewModel;
    public MainViewModel MainViewModel
    {
        get { return _mainViewModel; }
        set
        {
            _mainViewModel = value;
            OnPropertyChanged();
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        GV.MainViewModel.StartAssign(GV);
        MainViewModel = GV.MainViewModel;
        GV.MainViewModel.MainWindow = this;
        DataContext = MainViewModel;
 
    }
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

I tried with RelativeSource without success. If i create a variable in MainViewModel it works. Any help?


Answers (1)