从UserControl上的View中的属性访问数据

时间:2017-06-23 13:10:36

标签: c# wpf xaml user-controls

如何从View上的UserControl访问属性?

有这个观点:

stack.context.perform {
    _ = Measurement(sensorId: sensorId, fromDatetime: fromDatetime, pm10: pm10, pm25: pm25,
                    airQualityIndex: airQualityIndex, pollutionLevel: pollutionLevel, latitude: latitude, longitude: longitude,
                    source: source, windDeg: windDeg, windSpeed: windSpeed,
                    context: stack.context)
}

在这个视图中我有一个UserControl:

    public DataObject _DataObject ;

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

UserControl.cs

 <control:MyControl />

所以我的问题是,我可以在MyControl中访问_DataObject吗?

1 个答案:

答案 0 :(得分:0)

使用DependencyProperties并将其绑定到您的视图。

捷径是:propdp + tab

例如:

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.";
        }
    }

查看:

<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>

无论如何,请查看MVVM和详细信息What is a DepdencyProperty ?