gpt4 book ai didi

c# - 通过 xaml 设置用户控件自定义依赖属性

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:52 26 4
gpt4 key购买 nike

这是我的用户控件 (MonthCal) 的隐藏代码。

public partial class MonthCal : UserControl
{
public DayOfWeek StartDayOfWeek { get { return (DayOfWeek)GetValue(StartDayOfWeekProperty); } set { SetValue(StartDayOfWeekProperty, value); } }
public static readonly DependencyProperty StartDayOfWeekProperty = DependencyProperty.Register("StartDayOfWeek", typeof(DayOfWeek), typeof(MonthCellHeader), new UIPropertyMetadata(DayOfWeek.Sunday, StartDayOfWeek_PropertyChanged));
//...
}

此外,这是 MonthCal 的 xaml。

<UserControl x:Class="GCDR.MonthCal"
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"
mc:Ignorable="d">
<!-- ... -->
</UserControl>

因此,如何在 xaml 中设置“StartDayOfWeek”依赖属性?正如你们所知,以下代码是不可能的:

<UserControl ...
StartDayOfWeek="Sunday">
</UserControl>

请帮帮我。

最佳答案

您不能在 UserControl 的标记中使用依赖属性,但您可以在将用户控件的实例放置在某处时使用它,如下所示:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1">
<Grid>
<local:UserControl1 local:StartDayOfWeek="Friday" />
</Grid>
</Window>

在您的用户控件中,您可以像这样将一些其他属性绑定(bind)到您的依赖属性:

<UserControl x:Class="WpfApplication1.UserControl1"
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"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d" >
<Grid>
<Label Content="{Binding RelativeSource={RelativeSource AncestorType=local:UserControl1},Path=StartDayOfWeek}" />
</Grid>
</UserControl>

关于c# - 通过 xaml 设置用户控件自定义依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7898315/

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