如何将DataContext定义从代码隐藏移至XAML? [英] How to move the DataContext definition from code-behind to XAML?

查看:71
本文介绍了如何将DataContext定义从代码隐藏移至XAML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个对象,该对象在代码背后包含属性,并且想要将该对象设置为xaml中的datacontext。

I defined an object which contains properties in code-behind and, want to set the object to datacontext in xaml.

namespace WpfApplication4
{

    public partial class MainWindow : Window
    {
        public EquipInfo equip1;

        public MainWindow()
        {
            InitializeComponent();

            equip1 = new EquipInfo();
            //  setting here works fine but i want to do in xaml
            //textBox1.DataContext = equip1; 
        }
    }
}

这是xaml代码。 / p>

here's xaml code..

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Text="{Binding Path=PIN}" Height="23" 
                 HorizontalAlignment="Left" Margin="172,208,0,0" 
                 Name="textBox1" VerticalAlignment="Top" Width="120" />
    </Grid>
</Window>


推荐答案

您可以通过XAML将DataContext设置为公共属性。 blindmeis给出了一个很好的例子,说明了如何做到这一点。

You can set the DataContext via XAML to a public property. blindmeis has given a good example on how to do this.

您在Post中所做的不是设置DataContext,而是将控件的Text属性绑定到窗口的Property。这仅在设置了DataContext时有效。如果您不想执行MVVM(尽管我建议这样做),则另一种方法是在绑定中引用特定的元素:

What you did in your Post was not setting the DataContext, but binding the Text Property of your Control to a Property of the window. This only works if a DataContext is set. Another way to do that, if you don't want to do MVVM (which I'd recommend, though), is referencing specific Elements in your Binding:

1。 )将成员更改为AutoProperty或类似的

1.) Alter member to AutoProperty or similar

public EquipInfo equip1 {get;set;}

2。)给窗口命名

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="myWin"
    Title="MainWindow" Height="350" Width="525">

2。)按实例名称访问窗口属性

2.) Access Window Properties by instance name

<TextBox Text="{Binding ElementName=myWin, Path=equip1.PIN}"/>

在旁注中,确实使用<而是使用href = http://de.wikipedia.org/wiki/Model_View_ViewModel rel = nofollow> MVVM 。

这篇关于如何将DataContext定义从代码隐藏移至XAML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆