【发布时间】:2020-05-04 23:55:17
【问题描述】:
我正在循环浏览我的数据库项目,我正在显示样式单选按钮,这是我的代码:
public ObservableCollection<Product> products = new ObservableCollection<Product>(ProductsController.SelectAllProducts());
if (products.Count > 0)
{
foreach(var item in products)
{
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#004a80"));
RadioButton a = new RadioButton();
a.BorderThickness = new Thickness(1);
a.Background = Brushes.Green;
a.Foreground = new SolidColorBrush(Colors.Black);
a.BorderBrush = mySolidColorBrush;
a.Width = 118;
a.Height = 70;
a.Margin = new Thickness(5,0,0,5);
Style style = Application.Current.Resources["MyRadioButtonAsButtonStyle"] as Style;
a.Style = style;
a.ApplyTemplate();
a.Content = item.OrdinalNumber;
Image imgControl = (Image)a.Template.FindName("img", a);
Image imgControlWhite = (Image)a.Template.FindName("whiteImg", a);
TextBlock text = (TextBlock)a.Template.FindName("text", a);
a.Click += (object sender, RoutedEventArgs e) =>
{
var radioButton = sender as RadioButton;
MessageBox.Show(radioButton.Content.ToString());
};
text.Text = item.Title;
imgControl.Source = image;
spProducts.Children.Add(a);
}
}
在我的课程开始时,我从 Db 获得所有产品,并且我创建了与产品一样多的单选按钮,它看起来像这样:
如果 products.Count 为 8,我们将看到 8 个单选按钮,它们的样式为按钮:
虽然我想更改单选按钮上的背景颜色或标题,但我不想刷新整个屏幕,所以我添加了INotifyPropertyChanged,产品是Product 类型的列表,如下所示:
public class Product : INotifyPropertyChanged
{
#region Attributes
private string _ordinalNumber;
private string _title;
private string _description;
#endregion
#region Properties
public string OrdinalNumber
{
get { return _ordinalNumber; }
set { _ordinalNumber = value; NotifyPropertyChanged("OrdinalNumber"); }
}
public string Title
{
get { return _title; }
set { _title = value; NotifyPropertyChanged("Title"); }
}
public string Description
{
get { return _description; }
set { _description = value; NotifyPropertyChanged("Description"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
在同一文件的代码中的某处,我尝试修改标题:
var dbProduct = ProductController.Instance.GetProductByTitle(title);
var listItem = products.FirstOrDefault(x => x.OrdinalNumber == dbProduct.OrdinalNumber);
listItem.Title = "Test";
但是什么也没发生,我想因为 products 是创建单选按钮的来源,所以如果我更改该列表中某些项目的 Title,它会影响屏幕上的单选按钮,因为我正在使用 Title 道具当我显示单选按钮文本时。
任何形式的帮助都会很棒。
【问题讨论】:
-
你的装订在哪里?为什么不在 xaml 中这样做?
标签: c# wpf inotifypropertychanged