c# – 如何创建与成员变量的XAML绑定?

我是XAML和数据绑定的新手.我想在MainWindow.xaml中定义一个GUI控件,该控件从MainWindow.xaml.cs中的成员变量获取其数据.为简单起见,我只创建了一个显示计数器的程序以及一个增加计数器的按钮.

基于earlier threads我抬起头来,我想出了以下代码

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace XAMLBindingTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int Counter
        {
            get { return (int)GetValue(CounterProperty); }
            set { SetValue(CounterProperty,value); }
        }
        public static readonly DependencyProperty CounterProperty = 
            DependencyProperty.Register("Counter",typeof(int),typeof(MainWindow),new PropertyMetadata(null));

        public MainWindow()
        {
            Counter = 0;
            InitializeComponent();
        }

        private void incrementCounter(object sender,RoutedEventArgs e)
        {
            ++Counter;
        }
    }
}

MainWindow.xaml

<Window x:Class="XAMLBindingTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="140" Width="180">
    <Grid>
        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
            <TextBlock x:Name="txbCounter" HorizontalAlignment="Left" textwrapping="Wrap" Text="{Binding Counter}" VerticalAlignment="Top"/>
            <Button x:Name="btnIncrement" Content="Increment" Width="75" Click="incrementCounter"/>
        </StackPanel>
    </Grid>
</Window>

此示例编译,但TextBlock未显示计数器值.如何以正确的方式将TextBlock连接到Counter成员?

解决方法

尝试在窗口中添加名称”并使用“ElementName”绑定
<Window x:Class="XAMLBindingTest.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" Name="UI">
    <Grid>
        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
            <TextBlock x:Name="txbCounter" HorizontalAlignment="Left" textwrapping="Wrap" Text="{Binding ElementName=UI,Path=Counter}" VerticalAlignment="Top"/>
            <Button x:Name="btnIncrement" Content="Increment" Width="75" Click="incrementCounter"/>
        </StackPanel>
    </Grid>

</Window>

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...