binding 相关问题

这个标签在不同的环境中意味着不同的东西;考虑使用较少模糊的标签来代替或另外。常见含义包括:依赖项注入和数据绑定到对象和应用程序组件之间的绑定。

MAUI IsVisible 的问题

单击按钮时,我试图用 MVVM 隐藏一些框架和标签。 IsVisible() 只是不起作用。 其他绑定元素工作正常。 视图模型 命名空间 LoginApp.ViewModels {

回答 1 投票 0

在 ASP.NET MVC3 中将模型变量绑定到操作方法

我有一个具有以下操作方法的控制器 HomeController: [HttpPost] 公共 ActionResult 显示数据(MyViewModel myViewModel) { // 用 myViewModel 做点什么 }

回答 5 投票 0

如何从 listviewitem 模板绑定命令

我在 ResourceDictionary 中有一些模板,如下所示:

回答 0 投票 0

具有一项的 DataGrid 的 WPF SelectedItem 不起作用

当只有一个项目时,WPF DataGrid 的 SelectedItem 面临一个奇怪的问题。我在显示信息的 UI 中分为三个部分,即预购、订单和开发

回答 0 投票 0

当模式设置为 OneWay 时绑定对象被清除 - 使用 TwoWay 工作正常

我有一个简单的 wpf 弹出控件。当用户在文本框中输入错误的年龄时,我想显示弹出窗口。 我的代码片段 我有一个简单的 wpf Popup 控件。当用户在文本框中输入错误的年龄时,我想显示弹出窗口。 我的代码片段 <TextBox Name="TxtAge" LostFocus="TxtAge_OnLostFocus" ></TextBox> <Popup Name="InvalidAgePopup" IsOpen="{Binding IsAgeInvalid, Mode=OneWay}"/> 代码隐藏 private void TxtAge_OnLostFocus(object sender, RoutedEventArgs e) { var text = TxtAge.Text; double value = 0; if (Double.TryParse(text, out value)) { vm.IsAgeInvalid = false; } else { vm.IsAgeInvalid = true; } } 视图模型 public class AgeViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private bool _isAgeInvalid; public bool IsAgeInvalid { get { return _isAgeInvalid; } set { _isAgeInvalid = value; OnPropertyChanged(); } } } IsAgeInvalid 属性在输入无效年龄的文本框时设置。那时我想显示弹出窗口。而且我不想在弹出控件关闭时设置 IsAgeInvalid = false。 为此,我设置 Mode=OneWay IsOpen="{Binding IsAgeInvalid, Mode=OneWay} 当我输入错误的数据时,弹出窗口显示正常。当我关闭弹出窗口时,我的绑定对象正在被清除。 以下截图来自snoop工具。 绑定对象第一次出现。 弹窗关闭后,绑定对象清空。 绑定部分在 TwoWay 模式下工作正常,我不希望将 IsAgeInvalid 属性设置为 false,因为 IsOpen 设置为 false。 我试过设置 UpdateSourceTriger 和其他几种方法,弹出窗口关闭后绑定对象仍然被清除。 假设发生的事情是 WPF 错误或只是一个不值得失眠的怪癖,这里有一个(可能是显而易见的)解决方法: 视图模型: private bool _isAgeInvalid; public bool IsAgeInvalid { get { return _isAgeInvalid; } set { _isAgeInvalid = value; this.IsAgeValidationPopupOpen = valid; OnPropertyChanged(); } } private bool _isAgeValidationPopupOpen; public bool IsAgeValidationPopupOpen { get => _isAgeValidationPopupOpen; set { _isAgeValidationPopupOpen = value; OnPropertyChanged(); } } XAML: <Popup Name="InvalidAgePopup" IsOpen="{Binding IsAgeValidationPopupOpen, Mode=TwoWay}"/> 即使弹出窗口的关闭不应该破坏你的绑定,至少使用这种方法你有一个变量总是跟踪弹出窗口打开状态,另一个变量总是跟踪年龄有效性状态,所以可以说它是你的 UI 状态的更好表示. 你的代码有一些问题。您没有理由不将 TextBox 绑定到您的视图模型类。验证视图中的输入只是为了在视图模型上设置一个属性以指示验证失败是没有意义的。这样的属性必须是只读的,以确保不能随意设置。如果您选择在视图的代码隐藏中进行验证,那么只需从那里切换Popup。 但是,我建议实施INotifyDataErrorInfo(见下文)。 解释你的观察 根据您的陈述 “当我关闭弹出窗口时,我的绑定对象正在被清除。” 和 “我不希望 IsAgeInvalid 属性设置为 false,因为 IsOpen 设置为 false” 我得出结论,您不会通过将Popup设置为AgeViewModel.IsAgeInvalid来关闭false。相反,您直接设置 Popup.IsOpen 以关闭 Popup. 重要的一点是,如果 Binding.Mode 设置为 BindingMode.OneWay 并且直接(本地)设置依赖属性,则新值将清除/覆盖以前的值和值源,在您的情况下是一个 Binding 对象定义了 IsAgeInvalid 作为源属性。 这就是为什么您在关闭Binding(您的方式)时观察到Popup被删除的原因。 在本地设置依赖属性将始终清除以前的值和值源(Binding 和本地值具有相同的优先级)。 因为IsOpen绑定到IsAgeInvalid,你必须通过绑定来设置它(这是你明确不想做的)。 解决方案 1 使用Popup.IsOpen方法设置DependencyObject.SetCurrentValue属性。 这允许在不清除值源的情况下在本地分配新值(Binding): this.Popup.SetCurrentValue(Popup.IsOpenProperty, false); 方案二(推荐) 另外解决设计问题的正确解决方案是: 让您的视图模型类 AgeViewModel 实现 INotifyDataErrorInfo 以启用属性验证。 覆盖默认的验证错误反馈。当验证失败时,WPF 将自动在绑定目标周围绘制一个红色边框(在您的例子中为TextBox)。 您可以通过定义分配给附加的 ControlTemplate 属性的 Validation.ErrorTemplate 来非常轻松地自定义错误反馈。 以下示例使用解决方案 2) “使用 lambda 表达式和委托进行数据验证” 来自 如何添加验证以查看模型属性或如何实现 INotifyDataErrorInfo。只有属性 UserInput 被重命名为 Age 并且方法 IsUserInputValid 被重命名为 IsAgevalid 以使其解决您给定的场景。 AgeViewModel.cs class AgeViewModel : INotifyPropertyChanged, INotifyDataErrorInfo { // This property is validated using a lambda expression private string age; public string Age { get => this.age; set { // Use Method Group if (IsPropertyValid(value, IsAgeValid)) { this.age = value; OnPropertyChanged(); } } } // Constructor public AgeViewModel() { this.Errors = new Dictionary<string, IList<object>>(); } // The validation method for the UserInput property private (bool IsValid, IEnumerable<object> ErrorMessages) IsAgeValid(string value) { return double.TryParse(value, out _) ? (true, Enumerable.Empty<object>()) : (false, new[] { "Age must be numeric." }); } /***** Implementation of INotifyDataErrorInfo *****/ // Example uses System.ValueTuple public bool IsPropertyValid<TValue>( TValue value, Func<TValue, (bool IsValid, IEnumerable<object> ErrorMessages)> validationDelegate, [CallerMemberName] string propertyName = null) { // Clear previous errors of the current property to be validated _ = ClearErrors(propertyName); // Validate using the delegate (bool IsValid, IEnumerable<object> ErrorMessages) validationResult = validationDelegate?.Invoke(value) ?? (true, Enumerable.Empty<object>()); if (!validationResult.IsValid) { AddErrorRange(propertyName, validationResult.ErrorMessages); } return validationResult.IsValid; } // Adds the specified errors to the errors collection if it is not // already present, inserting it in the first position if 'isWarning' is // false. Raises the ErrorsChanged event if the Errors collection changes. // A property can have multiple errors. private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false) { if (!newErrors.Any()) { return; } if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors)) { propertyErrors = new List<object>(); this.Errors.Add(propertyName, propertyErrors); } if (isWarning) { foreach (object error in newErrors) { propertyErrors.Add(error); } } else { foreach (object error in newErrors) { propertyErrors.Insert(0, error); } } OnErrorsChanged(propertyName); } // Removes all errors of the specified property. // Raises the ErrorsChanged event if the Errors collection changes. public bool ClearErrors(string propertyName) { this.ValidatedAttributedProperties.Remove(propertyName); if (this.Errors.Remove(propertyName)) { OnErrorsChanged(propertyName); return true; } return false; } // Optional method to check if a particular property has validation errors public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any(); #region INotifyDataErrorInfo implementation // The WPF binding engine will listen to this event public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; // This implementation of GetErrors returns all errors of the specified property. // If the argument is 'null' instead of the property's name, // then the method will return all errors of all properties. // This method is called by the WPF binding engine when ErrorsChanged event was raised and HasErrors return true public System.Collections.IEnumerable GetErrors(string propertyName) => string.IsNullOrWhiteSpace(propertyName) ? this.Errors.SelectMany(entry => entry.Value) : this.Errors.TryGetValue(propertyName, out IList<object> errors) ? (IEnumerable<object>)errors : new List<object>(); // Returns 'true' if the view model has any invalid property public bool HasErrors => this.Errors.Any(); #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; #endregion protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void OnErrorsChanged(string propertyName) { this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } // Maps a property name to a list of errors that belong to this property private Dictionary<string, IList<object>> Errors { get; } } MainWindow.xaml AgeViewModel 中生成的错误消息由绑定引擎自动包装到 ValidationError 对象中。 我们可以通过引用 ValidationError.ErrorContent 属性来获取消息。 <Window> <Window.Resources> <ControlTemplate x:Key="ValidationErrorTemplate"> <StackPanel> <Border BorderBrush="Red" BorderThickness="1" HorizontalAlignment="Left"> <!-- Placeholder for the TextBox itself --> <AdornedElementPlaceholder x:Name="AdornedElement" /> </Border> <!-- Your Popup goes here. The Popup will close automatically once the error template is disabled by the WPF binding engine. Because this content of the ControlTemplate is already part of a Popup, you could skip your Popup and only add the TextBlock or whatever you want to customize the look --> <Popup IsOpen="True"> <!-- The error message from the view model is automatically wrapped into a System.Windows.Controls.ValidationError object. Our view moel returns a collection of messages. So we bind to the first message --> <TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red" /> </Popup> </StackPanel> </ControlTemplate> </Window.Resources> <!-- Enable validation and override the error template using the attached property 'Validation.ErrorTemplate' --> <TextBox Text="{Binding Age, ValidatesOnNotifyDataErrors=True}" Validation.ErrorTemplate="{StaticResource ValidationErrorTemplate}" /> </Window>

回答 2 投票 0

如何给绑定的listview绑定背景色?

我们如何在这里绑定颜色? DayItems.Add(new CustomCalendarViewDayItem(DateTime.Now.AddDays(1), "Tommorrow"));

回答 1 投票 0

为什么会出现这个异常?

我正在尝试解决一个任务(练习绑定和属性的使用),其中我有一个 MysteryClass,它包含一个方法并检查两个确定的值是否相等。如果是这样,它

回答 0 投票 0

.NET MAUI MVVM Picker 绑定到列表

我必须遗漏一些愚蠢或明显的东西,但我无法为我的生活弄清楚这个。我在我的视图模型中有一个对象列表,我试图绑定到一个选择器并显示'...

回答 1 投票 0

如何在有缺陷的 (111) 晶格表面上找到非等效结合位点

我有一个由 ATAT(合金理论自动化工具包)生成的缺陷表面,我必须创建一个 python 脚本来找到它对单齿分子的非等效结合位点。我在努力……

回答 0 投票 0

Prolog 绑定变量到另一个布尔变量的对面

我想创建一个子句,如果它的两个布尔参数相等且第三个参数为 1 或者它的两个布尔参数不相等且第三个参数为 0,则该子句将成立。我的第一个 atte...

回答 1 投票 0

为实际有效的绑定获取运行时错误

在 .NET 7.0 WPF 桌面应用程序中,我有这种样式,可以在禁用图像时将自定义灰度像素着色器应用于图像。样式在我的 App.xaml 文件中定义: <question vote="0"> <p>在 .NET 7.0 WPF 桌面应用程序中,我有这种样式,可以在禁用图像时将自定义灰度像素着色器应用于图像。样式在我的 App.xaml 文件中定义:</p> <pre><code>&lt;Style TargetType=&#34;Image&#34; x:Key=&#34;GrayscaleImageStyle&#34;&gt; &lt;Style.Triggers&gt; &lt;Trigger Property=&#34;IsEnabled&#34; Value=&#34;False&#34;&gt; &lt;Setter Property=&#34;Effect&#34;&gt; &lt;Setter.Value&gt; &lt;shaders:GrayscaleEffect Input=&#34;{Binding RelativeSource={RelativeSource Self}, Path=Source}&#34;/&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property=&#34;Opacity&#34; Value=&#34;0.5&#34;/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>现在样式运行良好,像素着色器正确应用于 IsEnabled 设置为 false 的图像。</p> <p>然而我注意到在运行时,我在输出调试窗口中收到一堆错误消息,如下所示:</p> <pre><code>System.Windows.Data Error: 40 : BindingExpression path error: &#39;Source&#39; property not found on &#39;object&#39; &#39;&#39;GrayscaleEffect&#39; (HashCode=1132111)&#39;. BindingExpression:Path=Source; DataItem=&#39;GrayscaleEffect&#39; (HashCode=1132111); target element is &#39;GrayscaleEffect&#39; (HashCode=1132111); target property is &#39;Input&#39; (type &#39;Brush&#39;) </code></pre> <p>我尝试了一些方法(例如使用 ImageSource 到 Brush 转换器(从未调用过)或使用绑定对象)无济于事。消息仍然很多,正如我提到的,即使效果完美,这也意味着绑定不需要工作。</p> <p>知道发生了什么以及如何摆脱这些无缝无用的消息吗?</p> </question> </body></html>

回答 0 投票 0

ng类绑定不是实时更新

你好我是angluar的新手,我制作了一个切换模态窗口(侧边导航) 你好我是 Angluar 的新手,我制作了一个切换模态窗口(侧导航) <mat-toolbar [ngClass]="rosterService.getBGColour(currentShift)"> <mat-toolbar-row class="w-full relative flex justify-between"> </mat-toolbar-row> </mat-toolbar> 这是 roster.service 中的 getBGColour getBGColour(shift) { let val = 0; const vals = []; if (shift?.uuid) { shift.tasks.forEach((task) => { vals.push(task.supplier.release_status); vals.push(task.resource.release_status); }); if (shift.release_status > 0 && vals.includes(3)) { val = 3; } else if (shift.release_status > 0 && (vals.includes(1) || vals.includes(undefined) || vals.includes(0))) { val = 1; } else if (shift.release_status === 0) { val = 0; } else { val = 2; } } return this.releaseStatus[val].colour; } 这是主视图 <mat-drawer class="w-3/5 dark:bg-primary" data-cy="creating-shift-drawer" [autoFocus]="false" [mode]="'over'" [position]="'end'" #matDrawerAddShift> <app-add-shift *ngIf="viewAddShift && matDrawerAddShift.opened" [viewMode]="viewMode" [addShiftData]="addShiftData" (closeSideBar)="closeSideNav('add')"> </app-add-shift> </mat-drawer> 当用户接受请求时,它显示某种颜色,效果很好,但问题是 我需要关闭模式并再次打开它以查看更改。 我想如果我像那样使用绑定,[ngClass]="method()",视图将自动更新,但事实并非如此。我在 google 和 chatGPT 上搜索,我尝试了 changeDetectorRef,订阅了 Roster.currentShift 你能告诉我如何解决这个问题吗? 谢谢 使用变化检测器 ref 手动检测变化。 getBGColour(shift) { this.cd.detectChanges(); let val = 0; const vals = []; . . 不要忘记在构造函数中注入 ChangeDetectorRef

回答 1 投票 0

IIS 在计算机重启后丢失 HTTPS Endpointn 证书

我知道我不是在计算机重启后丢失证书关联的人。 尤其: 在 IIS 中打开“站点绑定”对话框 查找我的 HTTPS 绑定 按“编辑...” 来自《SSL证书...

回答 2 投票 0

SwiftUI View 的 body 属性如何根据@State 的变化重新计算?

我正在学习 SwiftUI 并尝试建立一个连接: 视图有@State var @State 通过@Binding 传递给子视图 @State 是一个 Struct 类型的 propertyWrapper,它有 wrappedValue,projecte...

回答 0 投票 0

Docker:Nodemon 正在同步但没有重新运行

我是 Docker 的新手。 这些文件正在使用绑定安装同步更改,但 nodemon 没有重新运行。要查看更改,我必须停止容器并使用 docker compose up 重新启动。 我

回答 1 投票 0

WinUI 3, CommunityToolkit.WinUi, DataGridComboBoxColumn 存在Binding问题

在我的 ViewModel 类中,有一个名为 EmployeesList 的 [ObservableProperty],类型为 ObservableCollection, 同样,还有另一个名为 LeavesList 的 [ObservableProperty] 类型

回答 0 投票 0

TextField 绑定到可选数字

结构内容视图:查看{ @State private var data:双倍? var body:一些视图{ 堆栈 { 文本域(””, 值:$数据, ...

回答 0 投票 0

哪个前缀运算符!工程,全局或扩展绑定?

我做了一个反向bool绑定的测试代码如下,几乎包括了我能想到的绑定方式。 结构 TestView: 查看 { @State 私有变量 isOn: Bool = false @State private var par...

回答 0 投票 0

如何在 WPF C# 中将字符串绑定到标签内容?

我目前正在做一个项目,我主要关注后端,我知道这个 XAML 代码不是好的做法。我不是很习惯 INotifyPropertyChanged 接口,我真的很...

回答 2 投票 0

有没有办法更改键以在 python 中导航 tkinter MenuButton 选项?

Menubutton 小部件中的菜单打开似乎阻止了除箭头键、回车键和退出键之外的任何键输入。 我正在尝试在那个

回答 2 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.