0

How can you acces properties from a UserControl on a View?

Have this View:

    public DataObject _DataObject ;

    public MyView(DataObject dataObject )
    {
        InitializeComponent();
        Topmost = true;
        _DataObject = dataObject;
    }

And on this View I have a UserControl:

 <control:MyControl />

UserControl.cs

 public partial class MyControl : UserControl
 {
    public MyControl()
    {
        InitializeComponent();            
    }
 }

So my question is, can I acces _DataObject in MyControl?

user7998549
  • 131
  • 3
  • 15

1 Answers1

0

Use DependencyProperties and bind them to your View.

Short cut is : propdp + tab

For Example:

public partial class MainWindow : Window
    {



        public string MyName
        {
            get { return (string)GetValue(MyNameProperty); }
            set { SetValue(MyNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyNameProperty =
            DependencyProperty.Register("MyName", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty));


        public MainWindow()
        {
            InitializeComponent();

            MyName = "The main window.";
        }
    }

View:

<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        x:Name="Root">


    <TextBlock Text="{Binding MyName, ElementName=Root, Mode=OneWay}" />



</Window>

Anyway please check out MVVM and for extended information What is a DepdencyProperty ?

Peter
  • 1,655
  • 22
  • 44