2011-05-27 126 views
5
<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; 
      } 
     } 

    } 
} 

我需要添加到绑定源这个类。这是怎么回事?

+0

没有足够的信息,您甚至没有发布类标题。 – 2011-05-27 23:44:52

+0

你应该问问题,你自己会有信心回答。我不知道你的问题是什么。 – BentOnCoding 2011-05-28 00:00:43

+0

@ H.B和Robotsushi,我更新帖子。 – Mediator 2011-05-28 00:21:37

回答

3

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

1

DataContext = this;

将这个构造函数里面。