这是 XAML:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox Text="{Binding CB+Width,RelativeSource={RelativeSource AncestorType={x:Type Window}},Mode=TwoWay}"></TextBox>
</Grid>
</Window>
这是代码隐藏:
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 WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TB = new TextBox();
TB.Width = 200;
}
public ComboBox CB
{
get { return (ComboBox)GetValue(CBProperty); }
set { SetValue(CBProperty, value); }
}
// Using a DependencyProperty as the backing store for CB. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CBProperty =
DependencyProperty.Register("CB", typeof(ComboBox), typeof(MainWindow), null);
}
}
实际上,这DependencyProperty是一个自定义控件,但我将其替换为一个ComboBox,以便向您解释我的问题。
自定义控件不在同一个窗口中,我想将其值绑定Width到TextBox.
自定义控件位于不同的窗口中。这意味着有两个窗口,窗口 1 和窗口 2。自定义控件在窗口 1 中,文本框在窗口 2 中。我这样做是因为一个是主窗口,另一个是设置窗口。每当设置窗口更改设置时,您可以立即在主窗口中看到它。因此,我使用 DependencyProperty 将自定义控件存储在不同的窗口中并将其绑定到文本框。
现在我该怎么做?你能帮帮我吗?谢谢你。