[英]Bind multiple TextBoxes to one struct in WPF
如何將兩個TextBox對象綁定到System.Windows.Size 結構 ? 綁定只需要朝這個方向工作:
(textBox1.Text + textBox2.Text)=>(大小)
用戶在UI的TextBoxes中插入寬度和高度后,應創建Size對象。
XAML:
<TextBox Name="textBox_Width" Text="{Binding ???}" />
<TextBox Name="textBox_Height" Text="{Binding ???}" />
C#:
private Size size
{
get;
set;
}
是否有捷徑可尋?
編輯:大小是一個結構! 因此,“ someObject.Size.Width = 123”不起作用。 我需要調用Size-Constructor並設置someObject.Size = newSize
您能否僅公開2個屬性-模型中的width和height以及size屬性。 寬度和高度將出現在{Binding}表達式中,然后當您想要獲取size屬性時,它將基於這兩個字段進行初始化。
例如,您的模型可能類似於:
public class MyModel
{
public int Width{ get; set; }
public int Height{ get; set; }
public Size Size{ get{ return new Size( Width, Height ); }}
};
希望這可以幫助。
托尼
Window1.xaml.cs :
public partial class Window1 : Window
{
public static readonly DependencyProperty SizeProperty = DependencyProperty.Register("Size",
typeof(Size),
typeof(Window1));
public Size Size
{
get { return (Size)GetValue(SizeProperty); }
set { SetValue(SizeProperty, value); }
}
public Window1()
{
InitializeComponent();
DataContext = this;
_button.Click += new RoutedEventHandler(_button_Click);
}
void _button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Size.ToString());
}
}
Window1.xaml :
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBox Text="{Binding Size.Width}"/>
<TextBox Text="{Binding Size.Height}"/>
<Button x:Name="_button">Show Size</Button>
</StackPanel>
</Window>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.