【问题标题】:How binding textbox and property?如何绑定文本框和属性?
【发布时间】:2011-09-03 18:13:04
【问题描述】:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
    xmlns:System_Windows_Controls_Primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Toolkit"
    x:Class="SilverlightApplication5.MainPage"
    Width="640" Height="480">
    <StackPanel x:Name="LayoutRoot" Background="White">
        <TextBox x:Name="tbWidth" TextWrapping="Wrap" 
           Text="{Binding Mode=TwoWay, ValidatesOnExceptions=True, Path=RoomWidth}"/>
        </StackPanel>
</UserControl>

RoomWidth - 是属性。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication5
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private int roomWidth = 10;
        public int RoomWidth
        {
            get { return roomWidth; }
            set
            {
                if (value < 0 || value > 100)
                {
                    throw new Exception("Data not correct");
                }
                roomWidth = value;
            }
        }

    }
}

我需要将这个类添加到绑定源。这是怎么做到的?

【问题讨论】:

  • 没有足够的信息,你甚至没有发布课程标题。
  • 您应该提出自己有信心回答的问题。我不知道你的问题是什么。
  • @H.B 和 Robotsushi,我更新了帖子。

标签: wpf silverlight silverlight-4.0 binding


【解决方案1】:

ElementName 为例:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit" xmlns:System_Windows_Controls_Primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Toolkit"
    x:Class="SilverlightApplication5.MainPage"
    Width="640" Height="480"
    Name="control">

    <!-- ... -->
    <TextBox Text="{Binding ElementName=control, Mode=TwoWay, ValidatesOnExceptions=True, Path=RoomWidth}" x:Name="tbWidth" TextWrapping="Wrap"/>

如果您在使用类似的基本绑定时遇到问题,请阅读它。 (WPF/Silverlight)

【讨论】:

    【解决方案2】:

    DataContext = this;

    把它放在你的构造函数中。

    【讨论】:

      猜你喜欢
      • 2010-11-13
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多