-1

i want to use DependencyProperty for giving some value to somme userControl, but the value is not set int the userControl. I tried to modify the value in UserControl1 by hand and it works like this

here's a small project with this problem.

the MainWindow.xaml

<local:UserControl1 TextToShow="salutBG"/>

the UserControl1.xaml

<Label Content="{Binding TextToShow}"/>

the UserControl1.xaml.cs

public static readonly DependencyProperty ContactIdProperty =
DependencyProperty.Register(
    "TextToShow",                    // Nom de la propriété
    typeof(string),                // Type de la propriété
    typeof(UserControl1)
);

public string TextToShow
{
    get { return GetValue(ContactIdProperty)?.ToString() ?? ""; }
    set { SetValue(ContactIdProperty, value); }
}

public UserControl1()
{
    InitializeComponent();


    var ViewModel = new UserControl1Model();
    ViewModel.TextToShow =TextToShow;
    DataContext = ViewModel;
}

the UserControl1Model.cs

public class UserControl1Model
{
   public string TextToShow { get; set; } = "";
}

here's how it looks result and this is how I'd like it to look expected result

Emma
  • 431
  • 6
  • 19
  • There are a few things wrong. The dependency property declaration must follow a naming convention, ContactIdProperty must be named TextToShowProperty. The UserControl must not set its own DataContext. It must not have a private view model. Use a RelativeSource or ElementName Binding as shown in the answers to the duplicate questions. – Clemens Aug 10 '23 at 09:11
  • yes @Clemens, the answers work, but I need this value in my viewModel because I have a code that must behave differently depending on this value. how can i get it in the viewModel – Emma Aug 10 '23 at 09:18
  • You bind the control's property like `TextToShow="{Binding TextInViewModel}"`. The DataContext of the Window is set to a view model object with the TextInViewModel property. The UserControl inherits the DataContext from the Window. – Clemens Aug 10 '23 at 09:30
  • Thanks, but I don't really know what you mean. Could you show me an example or a link that explains how to do it, and is this the right way to do it in MVVM? – Emma Aug 10 '23 at 09:34
  • There are tons of examples here on StackOverflow or on the internet in general. – Clemens Aug 10 '23 at 09:35

0 Answers0