2012-08-27 29 views
1

我想创建自定义控制(或用户控件),其既具有正文块和文本框,如以下图:如何使用TextBlock创建自定义文本框?

enter image description here

无论是文本块和文本框文本属性将被绑定到数据库字段,并能够应用样式等这是最好的方法相同?

我想出了如下解决方案:

XAML用户控制:

<UserControl x:Class="TestDependency.TextBlox" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     x:Name="abc" 
     DataContext="{Binding RelativeSource={RelativeSource Self}}" > 
<Grid Width="170"> 
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="0,1,0,0" 
       Text="{Binding Path=Caption}" 
       VerticalAlignment="Top" Width="52" /> 
    <TextBox Height="25" HorizontalAlignment="Left" Margin="53,-2,0,0" 
      x:Name="TextBox1" 
      Text="{Binding Path=Value}" 
      VerticalAlignment="Top" Width="120" /> 
</Grid> 

后面的代码为用户控件:

public partial class TextBlox : UserControl 
{ 
    public TextBlox() 
    { 
     InitializeComponent(); 
    } 

    public static DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(TextBlox)); 
    public static DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(TextBlox)); 


    public string Caption 
    { 
     get 
     { 
      return (string)GetValue(CaptionProperty); 
     } 
     set 
     { 
      SetValue(CaptionProperty, value); 
     } 
    } 


    public string Value 
    { 
     get 
     { 
      return (string)GetValue(ValueProperty); 
     } 
     set 
     { 
      SetValue(ValueProperty, value); 
     } 
    } 

    static void ValueChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args) 
    { 
     TextBlox inst = (TextBlox)property; 
     inst.TextBox1.Text = (string)args.NewValue; 
    } 
} 

XAML的实际形式使用Usercontrol的地方:

01背后
<Grid x:Name="grdmain"> 
    <my:TextBlox Caption="{Binding XValue, Mode=TwoWay}" Value="{Binding WindowName, Mode=TwoWay}" 
     HorizontalAlignment="Left" Margin="246,197,0,0" x:Name="textBlox1" VerticalAlignment="Top" /> 
</Grid> 

代码:

public partial class MainWindow : Window 
{ 
    DataEntities dt = new DataEntities(); 
    CoOrdinate oCord; 
    public MainWindow() 
    { 
     InitializeComponent(); 
     Loaded += new RoutedEventHandler(MainWindow_Loaded); 
    } 

    void MainWindow_Loaded(object sender, RoutedEventArgs e) 
    { 
     oCord = dt.CoOrdinates.First(); 
     grdmain.DataContext = oCord; 
    } 
} 

仍然是绑定不起作用。但代码:

textBlox1.Caption = "test"; 

工作正常。我错在哪里?

回答

0

使用文本块和文本框创建用户控件,并将值绑定到该控件。

<YourUserControl TextBlockText="{Binding TextBlockText}" TextBoxText="{Binding TextBoxText, Mode=TwoWay}"/> 
+1

看起来像基本的想法,但我不认为绑定是完整的。 –

+0

这是对的,但我不知道索尼是否有ViewModel或不知道他如何得到他的值 – BvdVen

+2

您只需要为TextBox进行绑定2way – mlemay

相关问题