gpt4 book ai didi

WPF 将窗口标题绑定(bind)到属性

转载 作者:行者123 更新时间:2023-12-03 04:21:30 25 4
gpt4 key购买 nike

我正在尝试绑定(bind)从 Window 派生的类 (MainWindow) 的属性 (MyTitle) 的值。我创建了一个名为 MyTitleProperty 的依赖属性,实现了 INotifyPropertyChanged 接口(interface)并修改了 MyTitle 的 set 方法以调用 PropertyChanged 事件,并将“MyTitle”作为属性名称参数传递。我在构造函数中将 MyTitle 设置为“Title”,但是当窗口打开时标题为空白。如果我在 Loaded 事件上放置一个断点,则 MyTitle = "Title"但 this.Title = ""。这肯定是我没有注意到的非常明显的事情。请帮忙!

MainWindow.xaml

<Window
x:Class="WindowTitleBindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:this="clr-namespace:WindowTitleBindingTest"
Height="350"
Width="525"
Title="{Binding Path=MyTitle, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type this:MainWindow}}}"
Loaded="Window_Loaded">
<Grid>

</Grid>
</Window>

MainWindow.xaml.cs:

public partial class MainWindow : Window, INotifyPropertyChanged
{
public static readonly DependencyProperty MyTitleProperty = DependencyProperty.Register("MyTitle", typeof(String), typeof(MainWindow));

public String MyTitle
{
get { return (String)GetValue(MainWindow.MyTitleProperty); }
set
{
SetValue(MainWindow.MyTitleProperty, value);
OnPropertyChanged("MyTitle");
}
}

public MainWindow()
{
InitializeComponent();

MyTitle = "Title";
}

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}

最佳答案

public MainWindow()
{
InitializeComponent();

DataContext = this;

MyTitle = "Title";
}

那么你只需要在XAML中

Title="{Binding MyTitle}"

那么您就不需要依赖属性。

关于WPF 将窗口标题绑定(bind)到属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9603803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com