可扩展应用程序标记语言(XAML)是一种基于XML的声明式语言,用于在各种框架中初始化结构化值和对象。当问题是关于具有特定框架的XAML的使用时,还应该提供框架的标签,例如, [wpf](Windows Presentation Foundation),[silverlight],[windows-phone],[windows-store-apps](Windows 8商店应用),[win-universal-app],[xamarin.forms]或[工作流程 - 基础]
我使用 SqlCommand 属性实现了一个自定义 TextBox。 当 SqlCommand 具有绑定时 那么,SqlCommand 值字段是...
行为绑定在 CommunityToolkit.Maui v10 中不起作用
我已更新为使用 .NET 9,随后将 CommunityToolkit.Maui 更新为 v10.0,因为它是支持 .NET MAUI 的最新版本,但它似乎破坏了我的应用程序中的行为。
C# WPF 访问 DataGridTextColumn 标题内的 TextBox
我有这个代码。 我有这个代码。 <DataGridTextColumn Binding="{Binding nazwisko}" Header="Nazwisko" IsReadOnly="True" ElementStyle="{StaticResource verticalCenter}" FontSize="14" HeaderStyle="{StaticResource HeaderStyle}" Width="195"> <DataGridTextColumn.HeaderTemplate> <DataTemplate> <StackPanel> <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="-5,0,0,5" Content="{Binding Content, RelativeSource={RelativeSource Mode=TemplatedParent}}" Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Parent.ActualWidth}"/> <TextBox x:Name="txt_name" MinHeight="20" TextChanged="Filtr_TextChanged"/> </StackPanel> </DataTemplate> </DataGridTextColumn.HeaderTemplate> <DataGridTextColumn.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="Foreground" Value="{Binding FontColor}"/> </Style> </DataGridTextColumn.CellStyle> 我想清除文本框“txt_name”中的值。我有按钮“重置”,当他被单击时,文本框应该被清除。我怎样才能做到这一点?请帮忙:(. 您可以将 TextBox 值绑定到 祖先 DataContext。 如果您有将 ViewModel 绑定为 DataContext 的 Window: public class MainWindowViewModel : ObservableObject { private string _headerText = "InitialValue"; public string HeaderText { get => _headerText; set => SetProperty(ref _headerText, value); } public IRelayCommand Reset { get; } public MainWindowViewModel() { Reset = new RelayCommand(OnReset); } private void OnReset() { HeaderText = string.Empty; } } 然后你可以像这样使用它: ... <DataGridTextColumn.HeaderTemplate> <DataTemplate> <StackPanel> <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="-5,0,0,5" Content="{Binding Content, RelativeSource={RelativeSource Mode=TemplatedParent}}" Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Parent.ActualWidth}"/> <TextBox x:Name="txt_value" Text="{Binding DataContext.HeaderText, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" MinHeight="20"/> </StackPanel> </DataTemplate> </DataGridTextColumn.HeaderTemplate> ... <Button Content="Reset" Command="{Binding Reset}"/> ...
我的 WPF 应用程序生成的数据集每次可能具有不同的列数。 输出中包含对将用于应用格式设置的每列的描述。 一个
在 MAUI 中本地化选取器值的正确方法是什么?到目前为止我只有一个想法: 使用 LocalizationResourceManager.Maui。但对于选择器值来说,当应用程序本地化发生更改时,它不起作用
在 WPF C# 应用程序中将全局 dll 作为链接加载,而无需将其复制到输出目录中
我有以下问题: 我正在开发多个 WPF 应用程序,它们都必须使用相同的 dll。 这个 dll 位于我选择的目录中,但我不想将它复制到所有的罪恶中......
AutoSuggestBox的建议区域可以强制只向下扩展吗?
使用 AutoSuggestBox,其建议区域似乎在从控件向上或向下扩展之间有所不同。据推测,这是基于控件可用空间的最佳估计。 是...
我正在开发一个基于 XAML 的 C# 项目。 我有一个组合框,其中大多数情况下仅包含一个条目,但在某些情况下,它可能包含更多条目。 我想警告用户可能发生的情况...
假设一个元素声明了一个 x:DataType,那么任何无效的绑定都是编译器错误。如果在某些情况下不需要这样做,是否可以放弃外部 x:Dat 提供的保护...
当我想使用左上角的后退按钮或 Android 手机后退按钮返回时,应用程序会制作一个滑动动画,看起来不太好,而且有点问题。 那么我怎样才能禁用
来自 XAML 中只读属性的 OneWayToSource 绑定
我正在尝试以 OneWayToSource 作为模式绑定到 Readonly 属性,但这似乎无法在 XAML 中完成: 我正在尝试以 Readonly 作为模式绑定到 OneWayToSource 属性,但似乎无法在 XAML 中完成: <controls:FlagThingy IsModified="{Binding FlagIsModified, ElementName=container, Mode=OneWayToSource}" /> 我得到: 无法设置属性“FlagThingy.IsModified”,因为它没有可访问的设置访问器。 IsModified 是 DependencyProperty 上的只读 FlagThingy。我想将该值绑定到容器上的 FlagIsModified 属性。 需要明确的是: FlagThingy.IsModified --> container.FlagIsModified ------ READONLY ----- ----- READWRITE -------- 仅使用 XAML 可以吗? 更新:好吧,我通过在容器上设置绑定而不是在FlagThingy上修复了这种情况。但我还是想知道这是否可能。 OneWayToSource 的一些研究成果... 选项#1。 // Control definition public partial class FlagThingy : UserControl { public static readonly DependencyProperty IsModifiedProperty = DependencyProperty.Register("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata()); } <controls:FlagThingy x:Name="_flagThingy" /> // Binding Code Binding binding = new Binding(); binding.Path = new PropertyPath("FlagIsModified"); binding.ElementName = "container"; binding.Mode = BindingMode.OneWayToSource; _flagThingy.SetBinding(FlagThingy.IsModifiedProperty, binding); 选项#2 // Control definition public partial class FlagThingy : UserControl { public static readonly DependencyProperty IsModifiedProperty = DependencyProperty.Register("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata()); public bool IsModified { get { return (bool)GetValue(IsModifiedProperty); } set { throw new Exception("An attempt ot modify Read-Only property"); } } } <controls:FlagThingy IsModified="{Binding Path=FlagIsModified, ElementName=container, Mode=OneWayToSource}" /> 选项#3(真正的只读依赖属性) System.ArgumentException:“IsModified”属性无法进行数据绑定。 // Control definition public partial class FlagThingy : UserControl { private static readonly DependencyPropertyKey IsModifiedKey = DependencyProperty.RegisterReadOnly("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata()); public static readonly DependencyProperty IsModifiedProperty = IsModifiedKey.DependencyProperty; } <controls:FlagThingy x:Name="_flagThingy" /> // Binding Code Same binding code... Reflector给出答案: internal static BindingExpression CreateBindingExpression(DependencyObject d, DependencyProperty dp, Binding binding, BindingExpressionBase parent) { FrameworkPropertyMetadata fwMetaData = dp.GetMetadata(d.DependencyObjectType) as FrameworkPropertyMetadata; if (((fwMetaData != null) && !fwMetaData.IsDataBindingAllowed) || dp.ReadOnly) { throw new ArgumentException(System.Windows.SR.Get(System.Windows.SRID.PropertyNotBindable, new object[] { dp.Name }), "dp"); } .... 这是 WPF 的限制,是设计使然。 Connect 上有报道: 来自只读依赖属性的 OneWayToSource 绑定 我制定了一个解决方案,可以动态地将只读依赖属性推送到名为 PushBinding 的源,我在 博客中提到了这里。下面的示例将 OneWayToSource 从只读 DP 的 ActualWidth 和 ActualHeight 绑定到 DataContext 的 Width 和 Height 属性 <TextBlock Name="myTextBlock"> <pb:PushBindingManager.PushBindings> <pb:PushBinding TargetProperty="ActualHeight" Path="Height"/> <pb:PushBinding TargetProperty="ActualWidth" Path="Width"/> </pb:PushBindingManager.PushBindings> </TextBlock> PushBinding 通过使用两个依赖属性(Listener 和 Mirror)来工作。侦听器已绑定 OneWay 到 TargetProperty,并在 PropertyChangedCallback 中更新 Mirror 属性,该属性已绑定 OneWayToSource 到 Binding 中指定的任何内容。 可以在这里下载演示项目。 它包含源代码和简短的示例用法。 写下这个: 用途: <TextBox Text="{Binding Text}" p:OneWayToSource.Bind="{p:Paths From={x:Static Validation.HasErrorProperty}, To=SomeDataContextProperty}" /> 代码: using System; using System.Windows; using System.Windows.Data; using System.Windows.Markup; public static class OneWayToSource { public static readonly DependencyProperty BindProperty = DependencyProperty.RegisterAttached( "Bind", typeof(ProxyBinding), typeof(OneWayToSource), new PropertyMetadata(default(Paths), OnBindChanged)); public static void SetBind(this UIElement element, ProxyBinding value) { element.SetValue(BindProperty, value); } [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] [AttachedPropertyBrowsableForType(typeof(UIElement))] public static ProxyBinding GetBind(this UIElement element) { return (ProxyBinding)element.GetValue(BindProperty); } private static void OnBindChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((ProxyBinding)e.OldValue)?.Dispose(); } public class ProxyBinding : DependencyObject, IDisposable { private static readonly DependencyProperty SourceProxyProperty = DependencyProperty.Register( "SourceProxy", typeof(object), typeof(ProxyBinding), new PropertyMetadata(default(object), OnSourceProxyChanged)); private static readonly DependencyProperty TargetProxyProperty = DependencyProperty.Register( "TargetProxy", typeof(object), typeof(ProxyBinding), new PropertyMetadata(default(object))); public ProxyBinding(DependencyObject source, DependencyProperty sourceProperty, string targetProperty) { var sourceBinding = new Binding { Path = new PropertyPath(sourceProperty), Source = source, Mode = BindingMode.OneWay, }; BindingOperations.SetBinding(this, SourceProxyProperty, sourceBinding); var targetBinding = new Binding() { Path = new PropertyPath($"{nameof(FrameworkElement.DataContext)}.{targetProperty}"), Mode = BindingMode.OneWayToSource, Source = source }; BindingOperations.SetBinding(this, TargetProxyProperty, targetBinding); } public void Dispose() { BindingOperations.ClearAllBindings(this); } private static void OnSourceProxyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetCurrentValue(TargetProxyProperty, e.NewValue); } } } [MarkupExtensionReturnType(typeof(OneWayToSource.ProxyBinding))] public class Paths : MarkupExtension { public DependencyProperty From { get; set; } public string To { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { var provideValueTarget = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); var targetObject = (UIElement)provideValueTarget.TargetObject; return new OneWayToSource.ProxyBinding(targetObject, this.From, this.To); } } 尚未在样式和模板中进行测试,猜测它需要特殊的外壳。 这是另一个基于 SizeObserver 的附加属性解决方案,详细信息请参见此处 将只读 GUI 属性推回 ViewModel public static class MouseObserver { public static readonly DependencyProperty ObserveProperty = DependencyProperty.RegisterAttached( "Observe", typeof(bool), typeof(MouseObserver), new FrameworkPropertyMetadata(OnObserveChanged)); public static readonly DependencyProperty ObservedMouseOverProperty = DependencyProperty.RegisterAttached( "ObservedMouseOver", typeof(bool), typeof(MouseObserver)); public static bool GetObserve(FrameworkElement frameworkElement) { return (bool)frameworkElement.GetValue(ObserveProperty); } public static void SetObserve(FrameworkElement frameworkElement, bool observe) { frameworkElement.SetValue(ObserveProperty, observe); } public static bool GetObservedMouseOver(FrameworkElement frameworkElement) { return (bool)frameworkElement.GetValue(ObservedMouseOverProperty); } public static void SetObservedMouseOver(FrameworkElement frameworkElement, bool observedMouseOver) { frameworkElement.SetValue(ObservedMouseOverProperty, observedMouseOver); } private static void OnObserveChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var frameworkElement = (FrameworkElement)dependencyObject; if ((bool)e.NewValue) { frameworkElement.MouseEnter += OnFrameworkElementMouseOverChanged; frameworkElement.MouseLeave += OnFrameworkElementMouseOverChanged; UpdateObservedMouseOverForFrameworkElement(frameworkElement); } else { frameworkElement.MouseEnter -= OnFrameworkElementMouseOverChanged; frameworkElement.MouseLeave -= OnFrameworkElementMouseOverChanged; } } private static void OnFrameworkElementMouseOverChanged(object sender, MouseEventArgs e) { UpdateObservedMouseOverForFrameworkElement((FrameworkElement)sender); } private static void UpdateObservedMouseOverForFrameworkElement(FrameworkElement frameworkElement) { frameworkElement.SetCurrentValue(ObservedMouseOverProperty, frameworkElement.IsMouseOver); } } 在控件中声明附加属性 <ListView ItemsSource="{Binding SomeGridItems}" ut:MouseObserver.Observe="True" ut:MouseObserver.ObservedMouseOver="{Binding IsMouseOverGrid, Mode=OneWayToSource}"> 这是绑定到 Validation.HasError 的另一个实现 public static class OneWayToSource { public static readonly DependencyProperty BindingsProperty = DependencyProperty.RegisterAttached( "Bindings", typeof(OneWayToSourceBindings), typeof(OneWayToSource), new PropertyMetadata(default(OneWayToSourceBindings), OnBinidngsChanged)); public static void SetBindings(this FrameworkElement element, OneWayToSourceBindings value) { element.SetValue(BindingsProperty, value); } [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] [AttachedPropertyBrowsableForType(typeof(FrameworkElement))] public static OneWayToSourceBindings GetBindings(this FrameworkElement element) { return (OneWayToSourceBindings)element.GetValue(BindingsProperty); } private static void OnBinidngsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((OneWayToSourceBindings)e.OldValue)?.ClearValue(OneWayToSourceBindings.ElementProperty); ((OneWayToSourceBindings)e.NewValue)?.SetValue(OneWayToSourceBindings.ElementProperty, d); } } public class OneWayToSourceBindings : FrameworkElement { private static readonly PropertyPath DataContextPath = new PropertyPath(nameof(DataContext)); private static readonly PropertyPath HasErrorPath = new PropertyPath($"({typeof(Validation).Name}.{Validation.HasErrorProperty.Name})"); public static readonly DependencyProperty HasErrorProperty = DependencyProperty.Register( nameof(HasError), typeof(bool), typeof(OneWayToSourceBindings), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); internal static readonly DependencyProperty ElementProperty = DependencyProperty.Register( "Element", typeof(UIElement), typeof(OneWayToSourceBindings), new PropertyMetadata(default(UIElement), OnElementChanged)); private static readonly DependencyProperty HasErrorProxyProperty = DependencyProperty.RegisterAttached( "HasErrorProxy", typeof(bool), typeof(OneWayToSourceBindings), new PropertyMetadata(default(bool), OnHasErrorProxyChanged)); public bool HasError { get { return (bool)this.GetValue(HasErrorProperty); } set { this.SetValue(HasErrorProperty, value); } } private static void OnHasErrorProxyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetCurrentValue(HasErrorProperty, e.NewValue); } private static void OnElementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.NewValue == null) { BindingOperations.ClearBinding(d, DataContextProperty); BindingOperations.ClearBinding(d, HasErrorProxyProperty); } else { var dataContextBinding = new Binding { Path = DataContextPath, Mode = BindingMode.OneWay, Source = e.NewValue }; BindingOperations.SetBinding(d, DataContextProperty, dataContextBinding); var hasErrorBinding = new Binding { Path = HasErrorPath, Mode = BindingMode.OneWay, Source = e.NewValue }; BindingOperations.SetBinding(d, HasErrorProxyProperty, hasErrorBinding); } } } xaml 中的用法 <StackPanel> <TextBox Text="{Binding Value, UpdateSourceTrigger=PropertyChanged}"> <local:OneWayToSource.Bindings> <local:OneWayToSourceBindings HasError="{Binding HasError}" /> </local:OneWayToSource.Bindings> </TextBox> <CheckBox IsChecked="{Binding HasError, Mode=OneWay}" /> </StackPanel> 此实现特定于绑定 Validation.HasError WPF 不会使用 CLR 属性设置器,但似乎它会基于它进行一些奇怪的验证。 可能在你的情况下这可能没问题: public bool IsModified { get { return (bool)GetValue(IsModifiedProperty); } set { throw new Exception("An attempt ot modify Read-Only property"); } } 嗯...我不确定我是否同意这些解决方案。如何在属性注册中指定一个忽略外部更改的强制回调?例如,我需要实现一个只读 Position 依赖属性来获取 MediaElement 控件在用户控件内的位置。我是这样做的: public static readonly DependencyProperty PositionProperty = DependencyProperty.Register("Position", typeof(double), typeof(MediaViewer), new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, OnPositionChanged, OnPositionCoerce)); private static void OnPositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d as MediaViewer; } private static object OnPositionCoerce(DependencyObject d, object value) { var ctrl = d as MediaViewer; var position = ctrl.MediaRenderer.Position.TotalSeconds; if (ctrl.MediaRenderer.NaturalDuration.HasTimeSpan == false) return 0d; else return Math.Min(position, ctrl.Duration); } public double Position { get { return (double)GetValue(PositionProperty); } set { SetValue(PositionProperty, value); } } 换句话说,只需忽略更改并返回由不具有 public 修饰符的不同成员支持的值。 -- 在上面的例子中,MediaRenderer实际上是私有的MediaElement控件。 我解决此限制的方法是在类中仅公开 Binding 属性,将 DependencyProperty 完全保持为私有。我实现了一个“PropertyBindingToSource”只写属性(这个属性不是 DependencyProperty),它可以设置为 xaml 中的绑定值。在此只写属性的设置器中,我调用 BindingOperations.SetBinding 将绑定链接到 DependencyProperty。 对于OP的具体示例,它看起来像这样: FlatThingy 实现: public partial class FlatThingy : UserControl { public FlatThingy() { InitializeComponent(); } public Binding IsModifiedBindingToSource { set { if (value?.Mode != BindingMode.OneWayToSource) { throw new InvalidOperationException("IsModifiedBindingToSource must be set to a OneWayToSource binding"); } BindingOperations.SetBinding(this, IsModifiedProperty, value); } } public bool IsModified { get { return (bool)GetValue(IsModifiedProperty); } private set { SetValue(IsModifiedProperty, value); } } private static readonly DependencyProperty IsModifiedProperty = DependencyProperty.Register("IsModified", typeof(bool), typeof(FlatThingy), new PropertyMetadata(false)); private void Button_Click(object sender, RoutedEventArgs e) { IsModified = !IsModified; } } 请注意,静态只读 DependencyProperty 对象是私有的。在控件中,我添加了一个按钮,其单击由 Button_Click 处理。 在我的 window.xaml 中使用 FlatThingy 控件: <Window x:Class="ReadOnlyBinding.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:ReadOnlyBinding" mc:Ignorable="d" DataContext="{x:Static local:ViewModel.Instance}" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <TextBlock Text="{Binding FlagIsModified}" Grid.Row="0" /> <local:FlatThingy IsModifiedBindingToSource="{Binding FlagIsModified, Mode=OneWayToSource}" Grid.Row="1" /> </Grid> 请注意,我还实现了一个 ViewModel 用于绑定到此处未显示的视图模型。它公开了一个名为“FlagIsModified”的 DependencyProperty,您可以从上面的源代码中收集到。 它工作得很好,允许我以松散耦合的方式将信息从 View 推回 ViewModel,并明确定义信息流的方向。 您现在的装订方向错误。 每当您正在创建的控件上的 IsModified 发生更改时,OneWayToSource 将尝试更新容器上的 FlagIsModified。 您想要相反的结果,即将 IsModified 绑定到 container.FlagIsModified。 为此,您应该使用绑定模式 OneWay <controls:FlagThingy IsModified="{Binding FlagIsModified, ElementName=container, Mode=OneWay}" /> 枚举成员的完整列表:http://msdn.microsoft.com/en-us/library/system.windows.data.bindingmode.aspx
我有一个用户控件,其中包含带有一些元素的边框(StackPanel 中的图像和文本块) 当边框悬停时,是否可以更改纯 XAML 中的图像源? 我可以改变边框
我无法在 Windows 应用程序 WinUI 3 中绑定 NavigationViewItem 动态 x:Uid
我在新创建的 Windows 应用程序中使用 WinUI 3 NavigationView,我正在尝试使用 Template Studio for WinUI 来学习基础知识。我正在尝试使 NavigationViewItem 动态为
AvalonDock Dirkster:在 ILayoutUpdateStrategy 中将浮动 LayoutDocument 的位置设置为鼠标光标
在我的 LayoutUpdateStrategy 中,我将一些 LayoutDocuments 设置为 FloatingWindow。这是通过使用 Float() 来实现的。该窗口的位置是具有最小尺寸的主屏幕。有了 IsMaximized 我...
我有一个 MVVM (Prism) 应用程序。 UserControl 具有以下元素: 我有一个 MVVM (Prism) 应用程序。 UserControl 具有以下元素: <Grid> <ItemsControl x:Name="MyItemsControl" ItemsSource="{Binding Path=OrderCollection}"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox x:Name="MyTextBox"> <TextBox.Text> <Binding Path="ID" Mode="TwoWay"> <Binding.ValidationRules> <vr:OrderIDValidationRule/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <Button x:Name="MyButton"> </Button> </Grid> OrderIDValidationRule 只是一个简单的验证规则,用于检查 ID 是否在有效范围内。来自 ViewModel 的代码: public ObservableCollection<Order> OrderCollection; public class Order : BindableBase { private int? _id; public int? ID { get => _id; set => SetProperty(ref _id, value); } } 如果 MyTextBox(带有任何订单)有一些错误的值,有没有办法禁用 MyButton。例如,如果用户输入“abc”。在这种情况下,会显示验证错误,但绑定源不会更新 - 不确定 INotifyDataErrorInfo 是否可以在这里提供帮助 基于我的答案的示例https://stackoverflow.com/a/74293719/13349759 using System; using System.Reflection; using System.Windows; using System.Windows.Data; namespace CommonCore { public static class BindingExpressionHelper { private static readonly Func<BindingExpressionBase, DependencyObject, DependencyProperty, object> GetValueOfBindingExpression; static BindingExpressionHelper() { Type beType = typeof(BindingExpressionBase); var beMethod = beType .GetMethod("GetValue", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, new Type[] { typeof(DependencyObject), typeof(DependencyProperty) }) ?? throw new Exception("GetValue method not found."); var beFunc = (Func<BindingExpressionBase, DependencyObject, DependencyProperty, object>) beMethod.CreateDelegate(typeof(Func<BindingExpressionBase, DependencyObject, DependencyProperty, object>)); GetValueOfBindingExpression = beFunc; } /// <summary>Returns the source value of this binding expression.</summary> /// <param name="bindingExpression">The binding expression whose value to get.</param> /// <returns>The value of the binding expression received.</returns> public static object GetSourceValue(this BindingExpressionBase bindingExpression) { DependencyObject target = bindingExpression.Target; DependencyProperty targetProperty = bindingExpression.TargetProperty; var value = GetValueOfBindingExpression(bindingExpression, target, targetProperty); return value; } } } using System; using System.Collections.Generic; using System.Linq; using System.Windows; using static System.Windows.Media.VisualTreeHelper; namespace CommonCore.Helpers { public static partial class VisualTreeHelper { public static IEnumerable<DependencyObject> GetChildren(this DependencyObject parent) { ArgumentNullException.ThrowIfNull(parent); Queue<DependencyObject> queue = new Queue<DependencyObject>(16); queue.Enqueue(parent); while (queue.Count != 0) { DependencyObject current = queue.Dequeue(); yield return current; int count = GetChildrenCount(current); for (int i = 0; i < count; i++) { queue.Enqueue(GetChild(current, i)); } } } public static IEnumerable<T> GetChildren<T>(this DependencyObject parent) where T : DependencyObject => parent.GetChildren().OfType<T>(); public static T GetFirstChild<T>(this DependencyObject parent) where T : DependencyObject => (T)parent.GetChildren().FirstOrDefault(child => child is T); } } using System.Globalization; using System.Windows.Controls; using System.Windows.Data; using CommonCore; namespace Core2024.SO.AlexeyTitov.question79081208 { public class OrderIDValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { int id; switch (value) { case int _id: id = _id; break; case string text: id = int.Parse(text, cultureInfo); break; case BindingExpressionBase bindingExpression: var eee = bindingExpression.GetSourceValue(); var t = eee.GetType(); id = (int)(bindingExpression.GetSourceValue() ?? 0); break; default: id = int.MinValue; break; } if (id < 0 || id > 100) return new ValidationResult(false, "Значение вне диапазона [0..100]"); return ValidationResult.ValidResult; } } } using System.Collections.ObjectModel; namespace Core2024.SO.AlexeyTitov.question79081208 { public class Order : BaseInpc { private int? _id; public int? ID { get => _id; set => Set(ref _id, value); } } public class OrdersViewMode : BaseInpc { public ObservableCollection<Order> OrderCollection { get; } = new ObservableCollection<Order> ( Enumerable.Range(0, 20).Select(_ => new Order() { ID = Random.Shared.Next(-20, 120) }) ); } } <Window x:Class="Core2024.SO.AlexeyTitov.question79081208.TestErrorHandlerWindow" 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:Core2024.SO.AlexeyTitov.question79081208" mc:Ignorable="d" Title="TestErrorHandlerWindow" Height="450" Width="800"> <Window.DataContext> <local:OrdersViewMode/> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ItemsControl x:Name="MyItemsControl" ItemsSource="{Binding Path=OrderCollection}" Validation.Error="OnOrderError"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox x:Name="MyTextBox"> <TextBox.Text> <Binding Path="ID" Mode="TwoWay" NotifyOnValidationError="True"> <Binding.ValidationRules> <!--<local:OrderIDValidationRule ValidationStep="ConvertedProposedValue"/>--> <local:OrderIDValidationRule ValidationStep="ConvertedProposedValue" ValidatesOnTargetUpdated="True"/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <Button x:Name="MyButton" Grid.Row="1" Margin="5" Padding="15 5" Content="Click Me" HorizontalAlignment="Center" VerticalAlignment="Center"> </Button> <x:Code> <![CDATA[ private void OnOrderError(object sender, ValidationErrorEventArgs e) { bool hasError = ((DependencyObject)sender).GetChildren().Any(Validation.GetHasError); MyButton.IsEnabled = !hasError; } ]]> </x:Code> </Grid> </Window>
我有一个 [silverlight] WizardContainer 控件,它托管许多向导页面。 该向导非常适合其宿主形式。 如果页面内容较窄,则它不会扩展以填充容器...
System.Reflection.TargetInitationException - 调用目标已引发异常
我正在使用 Xamarin 开发一个学校项目。我对 Xamarin 不太熟悉,所以我会尽力解释我的问题。我的应用程序有一个课程页面和一个添加新课程页面。点击时...
错误:此 PlotModel 已被其他 PlotView 控件使用
我有两个选项卡绑定到一个视图模型,其中包含 oxyplot 的 PlotModel 和通过 DataTemplate 选择的视图模型。 当单击第一个选项卡时,视图模型已正确绑定,但是当
我创建了一个自定义控件,该控件应该用作项目视图中的按钮,但是,更改其文本的绑定不起作用。 CustomControls(Winui3类库项目)/CustomTableItem...
我创建了一个自定义控件,该控件应该用作项目视图中的按钮,但是,更改其文本的绑定不起作用。 CustomControls(Winui3类库项目)/CustomTableItem...