data-binding 相关问题

将两个数据/信息源绑定在一起并使它们保持同步的一般技术。

如何在 WPF 中将通用生成的复选框与枚举标志绑定?

我们有一个人可以拥有多种技能(力量、智力和运气)。在我们的 WPF 应用程序中,我们希望将这些技能绑定到复选框。当一个人的列表中包含这些技能时,那么...

回答 1 投票 0

自定义用户控件 + MVVM - WPF / Prism 框架

目前,我正在重构一个应用程序,其中有很多重复的 XAML 代码。我想改用自定义用户控件。我做了一个关于如何创建它们的教程,但现在我处于一个点上,...

回答 1 投票 0

WPF 组合框选择名称使用 ID

我有一个组合框,我试图在其中使用名称,但是当用户选择名称时,我想选择一个ID而不是名称。 这是我的 XAML: 我有一个 ComboBox,我尝试在其中使用名称,但是当用户选择名称时,我想选择 ID 而不是名称。 这是我的 XAML: <ComboBox x:Name="cb_tvrtkaID" Height="25" Margin="0,10,0,0" Loaded="cb_tvrtkaID_Loaded"/> 还有我的 C#: private void cb_tvrtkaID_Loaded(object sender, RoutedEventArgs e) { MSSQLConnect sql = new MSSQLConnect(); bool sqlIsConnected = sql.Connect(); string query = "SELECT tvrtkaId,tvrtkaNaziv from sifarnik.tvrtka"; SqlConnection connection = sql.GetConnection(); if (connection != null) { using (connection) { try { SqlCommand cmd = new SqlCommand(query, connection); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { cb_tvrtkaID.Items.Add(reader["tvrtkaNaziv"].ToString()); //cb_tvrtkaID.Items.Add(reader["tvrtkaId"].ToString()); cb_tvrtkaID.SelectedItem = reader["tvrtkaId"].ToString(); cb_tvrtkaID.DisplayMemberPath = reader["tvrtkaNaziv"].ToString(); } } } catch (Exception ex) { Debug.WriteLine(ex); } } } } 这给了我以下错误: System.Windows.Data Error: 40 : BindingExpression path error: 'Arbet-grad d' property not found on 'object' ''String' (HashCode=-1526763463)'. BindingExpression:Path=Arbet-grad d.o.o.; DataItem='String' (HashCode=-1526763463); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'Arbet-grad d' property not found on 'object' ''String' (HashCode=1553220975)'. BindingExpression:Path=Arbet-grad d.o.o.; DataItem='String' (HashCode=1553220975); target element is 'ComboBox' (Name='cb_tvrtkaID'); target property is 'NoTarget' (type 'Object') 如何解决此错误,以便显示名称但选择基础 ID? 一般来说,我建议用包含名称和 ID 的对象填充组合框。然后配置您的组合框以显示对象的名称。 <ComboBox x:Name="cb_tvrtkaID" Height="25" Margin="0,10,0,0" Loaded="cb_tvrtkaID_Loaded"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> 组合框中的对象将由以下方式定义: class cbItem { public string Name{get;set;} public string ID; public cbItem(string name, string id) { Name=name; ID=id;} } 在您的代码中,您可以添加以下项目: //[...] while (reader.Read()) { cbItem myCbItem = new cbItem(reader["tvrtkaNaziv"].ToString(), reader["tvrtkaId"].ToString(); cb_tvrtkaID.Items.Add(myCbItem ); //from outside this method, you can find the item of your combobox whose ID property is x, simply by iterating or with the help of Linq cb_tvrtkaID.SelectedItem = myCbItem; } //[...] 每次使用 cb_tvrtkaID.Items.Clear() 从 SQL 加载时,不要忘记清理组合框项目。 例如,您可以使用绑定到 cbItem 列表和转换器来实现与上述相同的结果

回答 1 投票 0

样式中WPF数据绑定的时序问题

我想在 WPF 绑定中立即进行数据验证,因此我在 UpdateSourceTrigger 中使用了 PropertyChanged。同时我想检测LostFocus,这是我修改DB的时间。而且,我

回答 1 投票 0

使用 TemplateColumns 将 WPF DataGrid 绑定到 DataTable

我已经尝试了一切但一无所获,所以我希望有人能给我一个顿悟的时刻。 我根本无法获得成功提取数据网格中数据的绑定。 我有一个数据表,可以...

回答 3 投票 0

将Cell中具有CustomClass的DataTable绑定到DataGrid WPF

我有数据网格。 我有数据网格。 <DataGrid ItemsSource="{Binding DataView}" x:Name="AttributeGrid" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" EnableColumnVirtualization="False" EnableRowVirtualization="False" DataContextChanged="AttributeGrid_DataContextChanged"> </DataGrid> 对于该 DataGrid 的单元格,我有自定义样式 <Style x:Key="DataGridDataViewCustomCellStyle" TargetType="{x:Type DataGridCell}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="DataGridCell"> <Grid> <ComboBox x:Name="ComboBoxCondition" IsEditable="True" ItemsSource="{Binding Values}" Visibility="Collapsed" SelectedValue="{Binding SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ValueID" DisplayMemberPath="ValueStr"/> <TextBox x:Name="TextBoxCondition" Text="{Binding TextValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> <DatePicker x:Name="DateCondition" Text="{Binding DateValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> </Grid> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding ValueType}" Value="Text"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Combobox"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Date"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Visible"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="True"> <Setter Property="Background" TargetName="TextBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="DateCondition" Value="Cornsilk"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="False"> <Setter Property="Background" TargetName="TextBoxCondition" Value="White"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="White"/> <Setter Property="Background" TargetName="DateCondition" Value="White"/> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> 如果 DataView 基于 List<object> gridAttributes = new List<AttributeItem>(); gridAttributes add some data ..... DataView = CollectionViewSource.GetDefaultView(gridAttributes); 一切都按预期进行。在 DataGridCell 中,我有 AttributeIem 对象,并且可以根据需要设置其样式。 但是,当 DataView 基于 DataTable 时,然后在 DataGridCell 中,由于某种原因我得到了 DataRowView,然后 Style 不起作用,一切都出错了。 RunDataTable.Rows.Clear(); RunDataTable.Columns.Clear(); RunDataTable.Columns.Add("SectionName"); RunDataTable.Columns.Add("RunName"); foreach (AttributeItem attr in gridAttributes) { RunDataTable.Columns.Add(attr.AttributeName, typeof(AttributeItem)); } DataRow row = RunDataTable.NewRow(); row["SectionName"] = section; row["RunName"] = name; foreach (AttributeItem item in gridAttributes) { row[item.AttributeName] = item; } RunDataTable.Rows.Add(row); DataView = new DataView(RunDataTable); 这是我收到的错误绑定列表 System.Windows.Data Error: 40 : BindingExpression path error: 'IsModified' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=IsModified; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'Values' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=Values; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable') System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=SelectedValue; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'SelectedValue' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'TextValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=TextValue; DataItem='DataRowView' (HashCode=47477033); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'DateValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=DateValue; DataItem='DataRowView' (HashCode=47477033); target element is 'DatePicker' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'ValueType' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=ValueType; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'ValueType' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=ValueType; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'ValueType' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=ValueType; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'IsModified' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=IsModified; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'IsModified' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=IsModified; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'Values' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=Values; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable') System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=SelectedValue; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'SelectedValue' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'TextValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=TextValue; DataItem='DataRowView' (HashCode=47477033); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'DateValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=DateValue; DataItem='DataRowView' (HashCode=47477033); target element is 'DatePicker' (Name=''); target property is 'Text' (type 'String') 任何建议我如何调整我的样式或代码隐藏以使其正常工作。 谢谢。 我尝试了不同的数据源方式。但不幸的是每次我都会遇到同样的错误 添加列: public static void RefreshColumnsFromModel(this DataGrid datagrid, DataGridRuns gridModel) { var myResourceDictionary = new ResourceDictionary(); myResourceDictionary.Source = new Uri("/SomeSource;component/Resources/SomeSource.xaml", UriKind.RelativeOrAbsolute); datagrid.Columns.Clear(); foreach (ColumnWithFilter column in gridModel.Columns.OrderBy(c => c.Index)) { if (column.IsReadOnly) { datagrid.Columns.Add( new DataGridTextColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, Binding = new Binding(column.ColumnBinding), CellStyle = myResourceDictionary["DataGridReadOnlyCellStyle"] as Style, HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate } ); } else { datagrid.Columns.Add( new DataGridTemplateColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, //Binding = new Binding(column.ColumnBinding), //HeaderTemplate = myResourceDictionary["HeaderTemplate"] as DataTemplate HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate, CellStyle = myResourceDictionary["DataGridDataViewCustomCellStyle"] as Style } ); } } } DataGridRuns 代表 DataGrid 的模型,一些用于过滤和排序的自定义行为 public class DataGridRuns : BaseClass { private List<AttributeItem> gridAttributes = new List<AttributeItem>(); public ObservableCollection<AttributeItem> GridAttributes { get { return new ObservableCollection<AttributeItem>(gridAttributes); } set { gridAttributes = value.ToList(); RaisePropertyChanged(); } } public DataTable RunDataTable { get; set; } = new DataTable("RunData"); private DataView dataView = null; public DataView DataView { get { return dataView; } } private ColumnWithFilter selectedColumn = null; public ColumnWithFilter SelectedColumn { get { return selectedColumn; } set { selectedColumn = value; RaisePropertyChanged(); } } public Action RefreshColumns; private List<ColumnWithFilter> columns = new List<ColumnWithFilter>(); public ObservableCollection<ColumnWithFilter> Columns { get { return new ObservableCollection<ColumnWithFilter>(columns); } set { columns = value.ToList(); RaisePropertyChanged(); } } public DataGridRuns() { } private List<AttributeItem> CreateAttributesFromInfo(IList<AttributeInfo> _attributes) { List<AttributeItem> result = new List<AttributeItem>(); try { foreach (var attr in _attributes) { result.Add(new AttributeItem(attr)); } } catch (Exception ex) { } return result; } public void AddRun(string section, string name, IList<AttributeInfo> _attributes, bool template = false) { var attr = CreateAttributesFromInfo(_attributes); if (gridAttributes == null || gridAttributes.Count() == 0) { gridAttributes = new List<AttributeItem>(attr); CreateColumns(); } DataRow row = RunDataTable.NewRow(); row["SectionName"] = section; row["RunName"] = name; foreach (AttributeItem item in gridAttributes) { row[item.AttributeName] = item; } RunDataTable.Rows.Add(row); dataView = new DataView(RunDataTable); //dataView = CollectionViewSource.GetDefaultView(RunDataTable); } public void ClearData() { gridAttributes.Clear(); gridAttributes = new List<AttributeItem>(); } public void CreateColumns() { RunDataTable.Rows.Clear(); RunDataTable.Columns.Clear(); columns = new List<ColumnWithFilter>(); ColumnWithFilter col = null; col = new ColumnWithFilter("Section Name", nameof(AttributeItem.SectionName)) { Index = 0, IsReadOnly = true, }; columns.Add(col); RunDataTable.Columns.Add("SectionName"); col = new ColumnWithFilter("Run Name", nameof(AttributeItem.RunName)) { Index = 1, IsReadOnly = true, }; columns.Add(col); RunDataTable.Columns.Add("RunName"); int colIndex = 1; foreach (AttributeItem attr in gridAttributes) { col = new ColumnWithFilter(attr.AttributeName, nameof(attr)) { Index = ++colIndex, IsReadOnly = false, }; columns.Add(col); RunDataTable.Columns.Add(attr.AttributeName, typeof(AttributeItem)); } } public void RefreshDataView() { foreach (DataRow item in RunDataTable.Rows) { item.ItemArray.ToList().ForEach(a => (a as AttributeItem)?.StartMarkingModifications()); } RaisePropertyChanged(nameof(DataView)); } public void RefreshPopupContent(string header = "") { selectedColumn = columns.Where(c => c.ColumnHeader.Equals(header)).FirstOrDefault(); if (selectedColumn == null) return; selectedColumn.RefreshFilterValues(gridAttributes .Where(a => !string.IsNullOrEmpty((string)GetPropertyValue(a, selectedColumn.ColumnBinding))) .Select(a => (string)GetPropertyValue(a, selectedColumn.ColumnBinding)).Distinct().ToList()); RaisePropertyChanged(nameof(SelectedColumn)); } public void Filtering() { UpdateDataViewRowFilter(); } private void UpdateDataViewRowFilter() { string rowFilter = string.Empty; foreach (ColumnWithFilter column in columns.Where(c => c.FilterIndex > 0)) { string andStr = !string.IsNullOrEmpty(rowFilter) ? " AND " : ""; switch (column.FilterIndex) { case 1: rowFilter += andStr + $"{column.ColumnBinding} IS NULL"; break; default: rowFilter += andStr + $"{column.ColumnBinding} = '{column.FilteredValue}'"; //filterResult = ((string)GetPropertyValue(attribute, column.ColumnBinding)).Equals(column.FilteredValue); break; } } (dataView as DataView).RowFilter = rowFilter; } public object GetPropertyValue(object obj, string propertyName) { return obj.GetType().GetProperty(propertyName)?.GetValue(obj, null); } } 这是我在 DataTable 中看到的,我希望在 DataGrid 中也能看到同样的结果 DataTable Visualizer 的屏幕截图 添加这是我在 UI 中看到的 具有列过滤的自定义网格 我不确定我是否正确理解了您的所有代码。我会根据我能理解的提供一个解决方案。 在数据表单元格中,您的类型为“AttributeItem”。具有路径“column.ColumnBinding”的绑定将从相应的单元格返回该类型的实例。 ValueType 和 IsModified 属性(在 ControlTemplate 中使用)属于此实例。 在这种情况下,我认为您错误地使用了 DataGridCell 样式更改。相反,您需要为单元格的内容创建一个数据模板。 <DataTemplate x:Key="DataGridDataViewCustomCellDataTemplate"> <Grid> <ComboBox x:Name="ComboBoxCondition" IsEditable="True" ItemsSource="{Binding Values}" Visibility="Collapsed" SelectedValue="{Binding SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ValueID" DisplayMemberPath="ValueStr"/> <TextBox x:Name="TextBoxCondition" Text="{Binding TextValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> <DatePicker x:Name="DateCondition" Text="{Binding DateValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> </Grid> <DataTemplate.Triggers> <DataTrigger Binding="{Binding ValueType}" Value="Text"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Combobox"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Date"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Visible"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="True"> <Setter Property="Background" TargetName="TextBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="DateCondition" Value="Cornsilk"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="False"> <Setter Property="Background" TargetName="TextBoxCondition" Value="White"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="White"/> <Setter Property="Background" TargetName="DateCondition" Value="White"/> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> 在模板 DataGridTemplateColumn 中,您需要创建一个带有 ContentControl 的模板,该模板将接受 Content 属性中路径“column.ColumnBinding”的绑定以及上述 ContentTemplate 属性中的模板。 private const string templateString = @" <DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> <ContentControl Content=""{{Binding {0}}}"" ContentTemplate=""{{DynamicResource DataGridDataViewCustomCellDataTemplate}}""/> </DataTemplate> "; public static void RefreshColumnsFromModel(this DataGrid datagrid, DataGridRuns gridModel) { var myResourceDictionary = new ResourceDictionary(); myResourceDictionary.Source = new Uri("/SomeSource;component/Resources/SomeSource.xaml", UriKind.RelativeOrAbsolute); datagrid.Columns.Clear(); foreach (ColumnWithFilter column in gridModel.Columns.OrderBy(c => c.Index)) { if (column.IsReadOnly) { datagrid.Columns.Add( new DataGridTextColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, Binding = new Binding(column.ColumnBinding), CellStyle = myResourceDictionary["DataGridReadOnlyCellStyle"] as Style, HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate } ); } else { string templateSource = string.Format(templateString, column.ColumnBinding); var template = XamlReader.Parse(templateSource); datagrid.Columns.Add( new DataGridTemplateColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, //Binding = new Binding(column.ColumnBinding), //HeaderTemplate = myResourceDictionary["HeaderTemplate"] as DataTemplate HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate, CellStyle = myResourceDictionary["DataGridDataViewCustomCellStyle"] as Style } ); } } } 不幸的是,我无法测试这段代码。但如果您提供重现这些情况的最少代码,我可以进行测试并准备有保证的工作版本。

回答 1 投票 0

我的 observableFIeld 显示空值是否有原因?

我有 MainActivity,我将 editTextValue 声明为 ObservableField 我想在单击按钮时使用 editTextValue.get() 获取它并将其传递给另一个函数。但我总是感到空虚。 班级

回答 1 投票 0

数据绑定从字符串中删除 html 标签

我想在数据绑定中使用 xml 资源字符串中的简单标签。 公共类 StringUtils { 公共静态字符串文本(字符串a){ 返回一个; } } XML: 我想在数据绑定中使用 xml 资源字符串中的简单标签。 public class StringUtils { public static String text(String a) { return a; } } XML: <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{StringUtils.text(@string/underlined_text)}" /> 字符串: <string name="underlined_text">This is a <u>underlined</u> text.</string> 最后当我调试文本方法时我意识到< u >标签被删除了。 很可能它从一开始就不存在。 在字符串资源中,识别的内联 HTML 元素(如 <u>)被解释为资源的一部分。如果您调用 getString(),这些 HTML 元素将被删除。如果您在 getText() 上调用 Resources,您将获得包含标记的 CharSequence(例如,UnderlineSpan)。 由于您在任何地方都使用 String,因此您的 HTML 元素将被忽略。 我不太确定为什么要以这种方式设置数据绑定。如果您使用: android:text="@string/underlined_text" 你会得到你想要的,而且更快。毕竟,StringUtils什么也没做。 但是,如果您确实确定要使用数据绑定: 使用您的字符串资源 ID 在 getText() 上调用 Resources 传递 CharSequence 以获取数据绑定表达式 或者,您可以将字符串资源的内容包装在 CDATA 中,以保持原始 HTML 完整。但在某些时候,您可能需要使用 Html.fromHtml() 或类似的东西来获取应用了格式的 CharSequence。 要在数据绑定中的字符串资源中使用 html 标签: 字符串: <string name="underlined_text">This is a &lt;u>underlined&lt;/u> text.</string> 布局: <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <import type="android.text.Html" /> </data> <your_root_view> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{Html.fromHtml(@string/underlined_text)}" /> </your_root_view> </layout> 在Android Studio 4.1.3中测试了此方法 您可以尝试使用 HTML 转义码: <string name="underlined_text">This is a &lt;u&gt;underlined&lt;/u&gt; text.</string> 我还想问这里是否真的需要数据绑定 - 你可以只使用android:text="@string/underlined_text" 编辑:还遇到了这个答案这可能对你有用 怎么样: android:text="@string/underlined_text" 您可以像这样更改定义的字符串以保留跨区字符串: <string name="underlined_text">This is a &lt;u&gt;underlined&lt;/u&gt; text.</string> 使用 @text/underlined_text 代替 @string/underlined_text。 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{@text/underlined_text}" /> 我没有在任何地方找到它的记录,但它有效。

回答 5 投票 0

WPF DataGrid - RowDetails DataContext

背景 我有以下 DataGrid,其中有两列用于描述和状态。它们绑定到一个名为 RowViewModels 的 ObservableCollection ,它作为 ...

回答 1 投票 0

Binding 和 x:Bind 的区别

UWP 中使用什么,Binding 或 x:Bind,它们之间有什么区别? 因为我看到很多帖子中人们使用 Binding,而我只在 UWP 中使用 x:Bind 进行 Bind。 仅在 MSDN 主页上

回答 3 投票 0

WPF MVVM 带参数的数据绑定?

所以我之前的问题似乎无法回答,所以我将根据自己的建议尝试一下。 我正在寻找的功能是让数据网格改变前景(甚至

回答 2 投票 0

C# - WPF - DataGrid - 在列之间共享绑定

我将此类的实例绑定到 DataGrid 公开课 SomeClass { 公共 int m_width { 得到;放; } 公共 int m_height { 得到;放; } ... 公共字符串[] m_content { 获取;放; ...

回答 1 投票 0

更改列表框中数据绑定文本块的前景色

我正在尝试根据绑定值更改列表框中数据绑定 TextBlock 的前景色。 我的代码如下:xaml 我正在尝试根据绑定值更改 TextBlock 中数据绑定 ListBox 的前景色。 我的代码如下:xaml <Grid.Resources> <converters:ColorConverter x:Key="ColorConverter"/> </Grid.Resources> <ListBox> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Name="TitleText"> <Run Foreground="{Binding Type, Converter={StaticResource ColorConverter}}" Text="&#x20b9;" /> </TextBlock> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 颜色转换器类: public class ColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { String Value = (String)value; if (Value.Equals("Credit")) return Colors.Green; else return Colors.Red; } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 当我运行代码时,没有错误,但颜色不会改变。 Lorem ipsum dolor sat amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut laboure et dolore magna aliqua。发酵蛋白 leo vel orci porta non pulvinar neque laoreet。 Commodo elit 坐在不准的位置。 Vulputate eu scelerisque felis imperdiet proin发酵leo vel orci。 Mattis ullamcorper velit sed ullamcorper morbi Tincidunt ornare Massa。 Sapien faucibus et molestie ac feugiat sed lectus. Id aliquet risus feugiat in ante metus: <TextBlock FontSize="12" FontWeight="Bold" Foreground="White"> <TextBlock.Text> <Binding XPath="Title"/> </TextBlock.Text> </TextBlock> ... sodales ut eu sem 整数: using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Ut enim ad minim veniam,quis nostrud 实习 ullamco labouris nisi ut aliquip ex ea commodo consequat..

回答 1 投票 0

BindingSource 似乎不包含在部分类中创建的属性

我正在尝试绑定到 Linq-To-SQL 查询的结果,我已将其设置为填充图形。 该图的 X 轴为“日期”线,Y 轴为“货币”线。有两个系列...

回答 2 投票 0

在asp.net mvc视图中使用textarea我想绑定数据

描述您的业务、成就和愿景(500字以内) <pre><code><div class="col-md-6"> <label>Describe Your Business, Achievement & Vision (Within 500 Words)</label> <textarea name="Description" type="text" placeholder="DESCRIBE YOUR BUSINESS, ACHIEVEMENT & VISION WITHIN 500 WORDS" required="" value="@Model.Description"></textarea> </div> </code></pre> <p>在使用textarea的asp.net mvc视图中我想绑定数据。调试后,我在<pre><code>@Model.Description.</code></pre>中获取数据。但在前端它没有显示。只是输入<pre><code>type = text;</code></pre>这些字段与数据绑定。但是定义为文本区域的字段,没有数据传入,它只显示占位符。谁能帮我解决这个问题吗??</p> </question> <answer tick="false" vote="0"> <p>对此有两种解决方案。 您可以编写如下代码片段:</p> <pre><code><div class="col-md-6"> <label>Describe Your Business, Achievement & Vision (Within 500 Words)</label> <textarea name="Description" type="text" placeholder="DESCRIBE YOUR BUSINESS, ACHIEVEMENT & VISION WITHIN 500 WORDS" required="">@Model.Description</textarea> </div> </code></pre> <p><strong>注意:</strong>“@Model.Description”应位于 <pre><code><textarea>@Model.Description</textarea></code></pre> 标签之间。在您的代码片段中,<pre><code>@Model.Description</code></pre> 作为 <pre><code>"value"</code></pre> 属性提供。这就是代码不适合您的原因。</p> <p>或另一种解决方案:使用 <pre><code>@Html.TextAreaFor</code></pre></p> <pre><code><div class="col-md-6"> <label>Describe Your Business, Achievement & Vision (Within 500 Words)</label> @Html.TextAreaFor(model => model.Description, new { style = "width: 200px; height: 150px;" , placeholder="DESCRIBE YOUR BUSINESS, ACHIEVEMENT & VISION WITHIN 500 WORDS", required="" } ) </div> </code></pre> <p>快乐编码!!</p> </answer> <answer tick="false" vote="0"> <p>textarea 标签助手根据提供给 asp-for 标签的模型属性名称显示 id 和 name 属性。它还显示属性验证所需的任何数据属性。</p> <pre><code><textarea type="text" asp-for="@Model.SupportSchedule.Description" class="form-control" name="Description"></textarea> </code></pre> <p>因此,使用此代码绑定问题并在 JavaScript 中获取复杂对象的数据效果很好。</p> <p>您可以检查<a href="https://www.learnrazorpages.com/razor-pages/tag-helpers/textarea-tag-helper" rel="nofollow noreferrer">文本区域</a></p> </answer> </body></html>

回答 0 投票 0

如何使用c#从wpf表单中仅选择下拉列表中的特定字段?

我有一个条件,检查隔间(卡车空)和目的(“离开成品”)这些是我唯一必填的字段,选择时必须与顶部密封和底部一起...

回答 1 投票 0

组合两个输入是一个日期对象

我的应用程序中有两个输入,我试图将它们组合在一个对象中(因为服务器期望一个对象) 模板: 我的应用程序中有两个输入,我试图将它们组合在一个对象中(因为服务器需要一个对象) 模板: <ion-item> <mat-form-field> <mat-label>Data Appuntamento</mat-label> <input matInput [matDatepicker]="picker" [(ngModel)]="this.DataPrenotazione" > <mat-hint>DD/MM/YYYY</mat-hint> <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> <ion-label>Ora Appuntamento</ion-label> <ngx-timepicker-field [format]="24" [(ngModel)]="this.OraPrenotazione" [minutesGap]="15"></ngx-timepicker-field> </ion-item> 然后我调用它来组合输入: combineDateTime(date: Date, time: Date): Date { const combinedDateTime = new Date(); combinedDateTime.setFullYear(date.getFullYear()); combinedDateTime.setMonth(date.getMonth()); combinedDateTime.setDate(date.getDate()); combinedDateTime.setHours(time.getHours()); combinedDateTime.setMinutes(time.getMinutes()); return combinedDateTime; } 当我尝试调用组合函数时,我得到“.getFullYear() 不是函数” this.combineDateTime(this.DataPrenotazione, this.OraPrenotazione) 我们从时间选择器获得的输出为 02:30,因此我们需要相应地分割它。我们可以对:进行字符串分割,然后使用一元+将分割后的字符串转换为数字,最后设置小时和分钟! combineDateTime(date: Date, time: string): Date { const combinedDateTime = new Date(); combinedDateTime.setFullYear(date.getFullYear()); combinedDateTime.setMonth(date.getMonth()); combinedDateTime.setDate(date.getDate()); const [hours, minutes] = time.includes(':') ? time.split(':') : [0, 0]; combinedDateTime.setHours(+hours); combinedDateTime.setMinutes(+minutes); return combinedDateTime; } 完整代码: TS: import { Component } from '@angular/core'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { MatInputModule } from '@angular/material/input'; import { MatFormFieldModule } from '@angular/material/form-field'; import { provideNativeDateAdapter } from '@angular/material/core'; import { FormsModule } from '@angular/forms'; import { NgxMaterialTimepickerModule } from 'ngx-material-timepicker'; import { CommonModule } from '@angular/common'; /** @title Basic datepicker */ @Component({ selector: 'datepicker-overview-example', templateUrl: 'datepicker-overview-example.html', standalone: true, providers: [provideNativeDateAdapter()], imports: [ MatFormFieldModule, MatInputModule, MatDatepickerModule, FormsModule, NgxMaterialTimepickerModule, CommonModule, ], }) export class DatepickerOverviewExample { OraPrenotazione: string = '00:00'; DataPrenotazione: Date = new Date(); combinedDateTime: any = null; combineDateTime(date: Date, time: string): Date { const combinedDateTime = new Date(); combinedDateTime.setFullYear(date.getFullYear()); combinedDateTime.setMonth(date.getMonth()); combinedDateTime.setDate(date.getDate()); const [hours, minutes] = time.includes(':') ? time.split(':') : [0, 0]; combinedDateTime.setHours(+hours); combinedDateTime.setMinutes(+minutes); return combinedDateTime; } } HTML: <mat-form-field> <mat-label>Data Appuntamento</mat-label> <input matInput [matDatepicker]="picker" [(ngModel)]="this.DataPrenotazione" /> <mat-hint>DD/MM/YYYY</mat-hint> <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> <label>Ora Appuntamento</label> <ngx-timepicker-field [format]="24" [(ngModel)]="this.OraPrenotazione" [minutesGap]="15" ></ngx-timepicker-field> <button (click)="combinedDateTime = combineDateTime(DataPrenotazione, OraPrenotazione)" > combine </button> Final DATE: {{combinedDateTime | date : 'full'}} Stackblitz 演示

回答 1 投票 0

如何传播 WPF 数据绑定期间发生的错误和异常?

我经常发现我不小心破坏了应用程序中的数据绑定。通过重命名属性而不是在 XAML 中重命名它,或者通过属性抛出某些异常......

回答 4 投票 0

如何设置GridView单元格背景颜色

我想根据绑定的Burshdata设置单元格的背景颜色,但它不会填充整个单元格。 展示我的问题的图像: 这是我的代码: ...

回答 1 投票 0

WPF:如何设置GridView单元格背景颜色

我想根据绑定的Burshdata设置单元格的背景颜色,但它不会填充整个单元格。 演示我的问题的图像: 这是我的代码: ...

回答 1 投票 0

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