- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个自定义控件 - 为自动完成文本框实现。我从以下问题中得到了所有想法 Create a Custom Control with the combination of multiple controls in WPF C# .在该自定义控件中,他们建议使用以下代码来添加项目,它完美地工作并且双向绑定(bind)也是如此。
(this.ItemsSource as IList<string>).Add(this._textBox.Text);
但是,我将以下代码更改为未知对象,所以我更改了IList<string>
至 IList<object>
(this.ItemsSource as IList<object>).Add(item);
XAML:
<local:BTextBox
ItemsSource="{Binding Collection}"
ProviderCommand="{Binding AutoBTextCommand}"
AutoItemsSource="{Binding SuggCollection}" />
但它没有更新 ViewModel 属性 Collection
。我也在 xaml 中尝试了以下更改
ItemsSource="{Binding Collection, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
我不知道我哪里做错了。
功能:TextBox
在CustomControl
里面接受用户的输入并触发 ProviderCommand
,该命令根据用户输入过滤远程数据,并通过 AutoItemsSource
发送过滤后的集合,此属性绑定(bind)为 ItemsSource
的 ListBox
里面CustomControl
选择项目。我们可以从 ListBox
中选择项目元素,通过点击元素,触发命令 AddCommand
在 CustomControl
中类,它在ItemSource
中添加所选项目CustomControl
的属性.我在此属性 中遇到双向绑定(bind)问题 ItemsSource
。我们只能从这个属性中获取作为集合的选定项。
这是我的完整源代码
自定义控件 C# 代码:
public class BTextBox : ItemsControl
{
static BTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BTextBox), new FrameworkPropertyMetadata(typeof(BTextBox)));
}
#region Private Members
private TextBox _textBox;
private ItemsControl _itemsView;
#endregion
#region Dependency Property Private Members
public static readonly DependencyProperty ProviderCommandProperty = DependencyProperty.Register("ProviderCommand", typeof(ICommand), typeof(BTextBox), new PropertyMetadata(null));
public static readonly DependencyProperty AutoItemsSourceProperty = DependencyProperty.Register("AutoItemsSource", typeof(IEnumerable<dynamic>), typeof(BTextBox), new PropertyMetadata(null, OnItemsSourceChanged));
#endregion
#region Dependency Property Public members
public IEnumerable<dynamic> AutoItemsSource
{
get { return (IEnumerable<dynamic>)GetValue(AutoItemsSourceProperty); }
set { SetValue(AutoItemsSourceProperty, value); }
}
#endregion
#region Listener Methods
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tb = d as BTextBox;
if ((e.NewValue != null) && ((tb.ItemsSource as IList<object>) != null))
{
(tb.AutoItemsSource as IList<object>).Add(e.NewValue);
}
}
#endregion
#region Override Methods
public override void OnApplyTemplate()
{
this._textBox = this.GetTemplateChild("PART_TextBox") as TextBox;
this._itemsView = this.GetTemplateChild("PART_ListBox") as ItemsControl;
this._textBox.TextChanged += (sender, args) =>
{
if (this.ProviderCommand != null)
{
this.ProviderCommand.Execute(this._textBox.Text);
}
};
base.OnApplyTemplate();
}
#endregion
#region Command
public ICommand ProviderCommand
{
get { return (ICommand)GetValue(ProviderCommandProperty); }
set { SetValue(ProviderCommandProperty, value); }
}
public ICommand AddCommand
{
get
{
return new DelegatingCommand((obj) =>
{
(this.ItemsSource as IList<object>).Add(obj);
});
}
}
#endregion
}
Generic.xaml代码是
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleControl">
<Style TargetType="{x:Type local:BTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:BTextBox}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="PART_TextBox" Grid.Row="0" Width="*" VerticalAlignment="Center" />
<ListBox ItemsSource="{TemplateBinding AutoItemsSource}" Grid.Row="1" x:Name="PART_ListBox_Sugg" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Value.IsChecked}" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:BTextBox}}, Path=AddCommand}" CommandParameter="{Binding }" Foreground="#404040">
<CheckBox.Content>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding }" Visibility="Visible" TextWrapping="Wrap" MaxWidth="270"/>
</StackPanel>
</CheckBox.Content>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
MainWindow.xaml代码是
<Window x:Class="SampleControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleControl"
Title="MainWindow" Height="400" Width="525">
<Grid>
<local:BTextBox
ItemsSource="{Binding Collection}"
ProviderCommand="{Binding AutoBTextCommand}"
AutoItemsSource="{Binding SuggCollection}" />
</Grid>
</Window>
MainWindow.xaml 的 C# 代码背后的代码
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new StringModel();
}
}
我有两个 ViewModel
ViewModel #1 StringModel
class StringModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<string> _collection = new ObservableCollection<string>();
private ObservableCollection<string> _suggCollection = new ObservableCollection<string>();
private ObservableCollection<string> _primaryCollection = new ObservableCollection<string>();
public ObservableCollection<string> Collection
{
get { return _collection; }
set
{
_collection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
}
}
public ObservableCollection<string> SuggCollection
{
get { return _suggCollection; }
set
{
_suggCollection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SuggCollection"));
}
}
public StringModel()
{
_primaryCollection = new ObservableCollection<string> {
"John", "Jack", "James", "Emma", "Peter"
};
}
public ICommand AutoBTextCommand
{
get
{
return new DelegatingCommand((obj) =>
{
Search(obj as string);
});
}
}
private void Search(string str)
{
SuggCollection = new ObservableCollection<string>(_primaryCollection.Where(m => m.ToLowerInvariant().Contains(str.ToLowerInvariant())).Select(m => m));
}
}
ViewModel #2 IntModel
class IntModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<int> _collection = new ObservableCollection<int>();
private ObservableCollection<int> _suggCollection = new ObservableCollection<int>();
private ObservableCollection<int> _primaryCollection = new ObservableCollection<int>();
public ObservableCollection<int> Collection
{
get { return _collection; }
set
{
_collection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
}
}
public ObservableCollection<int> SuggCollection
{
get { return _suggCollection; }
set
{
_suggCollection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SuggCollection"));
}
}
public IntModel()
{
_primaryCollection = new ObservableCollection<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 16, 17, 18, 19, 20 };
}
public ICommand AutoBTextCommand
{
get
{
return new DelegatingCommand((obj) =>
{
Search(obj as string);
});
}
}
private void Search(string str)
{
int item = 0;
int.TryParse(str, out item);
SuggCollection = new ObservableCollection<int>(_primaryCollection.Where(m => m == item).Select(m => m));
}
}
最佳答案
首先,这篇文章更适合 CodeReview。
其次,我可以想象,你确实想做什么。为了缩短时间,我建议您在您的案例中不要使用通用集合。
我稍微修改了控件:
public class BTextBox : ItemsControl {
static BTextBox() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(BTextBox), new FrameworkPropertyMetadata(typeof(BTextBox)));
}
private TextBox _textBox;
private ItemsControl _itemsView;
public static readonly DependencyProperty ProviderCommandProperty = DependencyProperty.Register("ProviderCommand", typeof(ICommand), typeof(BTextBox), new PropertyMetadata(null));
public static readonly DependencyProperty AutoItemsSourceProperty = DependencyProperty.Register("AutoItemsSource", typeof(IEnumerable), typeof(BTextBox), new PropertyMetadata(null, OnItemsSourceChanged));
public IEnumerable AutoItemsSource {
get {
return (IEnumerable)GetValue(AutoItemsSourceProperty);
}
set {
SetValue(AutoItemsSourceProperty, value);
}
}
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var tb = d as BTextBox;
if ((e.NewValue != null) && ((tb.ItemsSource as IList) != null)) {
foreach (var item in e.NewValue as IEnumerable) {
(tb.AutoItemsSource as IList).Add(item);
}
}
}
public override void OnApplyTemplate() {
this._textBox = this.GetTemplateChild("PART_TextBox") as TextBox;
this._itemsView = this.GetTemplateChild("PART_ListBox_Sugg") as ItemsControl;
this._itemsView.ItemsSource = this.AutoItemsSource;
this._textBox.TextChanged += (sender, args) => {
this.ProviderCommand?.Execute(this._textBox.Text);
};
base.OnApplyTemplate();
}
public ICommand ProviderCommand {
get {
return (ICommand) this.GetValue(ProviderCommandProperty);
}
set {
this.SetValue(ProviderCommandProperty, value);
}
}
public ICommand AddCommand {
get {
return new RelayCommand(obj => {
(this.ItemsSource as IList)?.Add(obj);
});
}
}
}
然后我修复了您的 XAML,使它甚至可以编译和运行:
<Style TargetType="{x:Type local:BTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:BTextBox}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="PART_TextBox" Grid.Row="0" VerticalAlignment="Center" />
<ListBox ItemsSource="{TemplateBinding AutoItemsSource}" Grid.Row="1" x:Name="PART_ListBox_Sugg" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:BTextBox}}, Path=AddCommand}" CommandParameter="{Binding}" Foreground="#404040">
<CheckBox.Content>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding }" Visibility="Visible" TextWrapping="Wrap" MaxWidth="270"/>
</StackPanel>
</CheckBox.Content>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
最后说一句很有值(value)的话:
永远不要在您的 ItemsSources 上允许 setter。如果覆盖它们,绑定(bind)将中断。使用 .Clear()
和 .Add()
代替,如下所示:
public class StringModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private readonly ObservableCollection<string> _collection = new ObservableCollection<string>();
private readonly ObservableCollection<string> _suggCollection = new ObservableCollection<string>();
private readonly ObservableCollection<string> _primaryCollection = new ObservableCollection<string>();
public ObservableCollection<string> Collection => this._collection;
public ObservableCollection<string> SuggCollection => this._suggCollection;
public StringModel() {
this._primaryCollection.Add("John");
this._primaryCollection.Add("Jack");
this._primaryCollection.Add("James");
this._primaryCollection.Add("Emma");
this._primaryCollection.Add("Peter");
}
public ICommand AutoBTextCommand {
get {
return new RelayCommand(obj => {
this.Search(obj as string);
});
}
}
private void Search(string str) {
this.SuggCollection.Clear();
foreach (var result in this._primaryCollection.Where(m => m.ToLowerInvariant().Contains(str.ToLowerInvariant())).Select(m => m)) {
this.SuggCollection.Add(result);
}
}
}
注意
因为我没有您的DelegateCommand
-实现,所以我使用了我的RelayCommand
。您可以在没有任何问题的情况下更改它。我认为它是同一件事,但名称不同。
您也可以考虑从一开始就显示您的建议。这可能会提供更好的用户体验,但这只是我的意见
关于c# - WPF 自定义控件依赖属性中未知对象的双向绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187879/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!