gpt4 book ai didi

c# - 银光 4 : How to make a combobox refresh its ItemsSource on open

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:59 24 4
gpt4 key购买 nike

我想在打开时刷新 Silverlight 4 组合框的内容。

这似乎是一件愚蠢而简单的事情,但我终究无法找到直接的答案。

我在 Silverlight 4 应用程序中有一个表单,其中包含一个列出销售订单编号的组合框。许多人会同时打开此表单,因此我希望它在打开时回调到 Web 服务并刷新其内容。

我发现的最接近的是:
http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx

..我无法完成工作,也无济于事。该示例中没有任何内容允许我在下拉菜单打开时重新填充它。

我正在使用 MVVM 并使用交互类将组合框的打开事件泵入我的 ViewModel。在那里,我调用 web 服务并重置组合框的 ItemsSource 绑定(bind)到的基础属性。不起作用 - 下拉列表闪烁一秒钟,然后打开,但为空。

更新:

XAML:

<ComboBox x:Name="cmbOrderNumber" Width="125" 
ItemsSource="{Binding ActiveSalesOrderNumbers, Mode=TwoWay}"
IsEnabled="{Binding OrderSelectorEnabled}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<inf:InvokeDelegateCommandAction Command="{Binding SalesOrderSelectedCommand}" CommandParameter="{Binding ElementName=cmbOrderNumber, Path=SelectedValue}"></inf:InvokeDelegateCommandAction>
</i:EventTrigger>
<i:EventTrigger EventName="DropDownOpened">
<inf:InvokeDelegateCommandAction Command="{Binding SalesOrderOpenedCommand}"></inf:InvokeDelegateCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>

C#:

 public void OnSalesOrderOpenedCommand(object o)
{
_companyContext.Load(_companyContext.GetSales_Order_Numbers_FromDateQuery(_lastSalesOrderRequest), q =>
{
if (!q.HasError)
{
q.Entities.ToList().ForEach(e =>
{
ActiveSalesOrderNumbers.Add(e.Sales_Order_Number);
});
_lastSalesOrderRequest = DateTime.Now;
}
else
{
throw new Exception("Error updating sales order number list.");
}
}, null);
}

事件被触发,我看到数据按预期从服务返回,并将新项目添加到 ActiveSalesOrderNumbers,这是一个 ObservableCollection。下拉列表不更新,没有新记录。

最佳答案

您的项目列表是什么样的?如果你的ItemsSource被绑定(bind)到 ObservableCollection<T>在您的 ViewModel 上,那么您应该能够从该集合和 ComboBox 中添加/删除项目项目将正确更新。 ComboBox 因一旦设置一次就真的搞砸了你的绑定(bind)而臭名昭着。我建议不要尝试替换整个 ItemsSource,而是使用 ObservableCollection<T> , Clear()然后Add(...) .

我现在正在做一个项目,我已经完成了这件事,所以我可以验证它是否有效。

编辑:

主页.xaml

<ComboBox
x:Name="comboBox"
ItemsSource="{Binding ActiveSalesOrderNumbers}"
HorizontalAlignment="Center"
Width="200"
Height="27"
Margin="30">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel
Orientation="Horizontal">
<TextBlock>
<Run Text="{Binding SalesOrderNumber}"/>
<Run Text="{Binding LastModified}"/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
<i:Interaction.Triggers>
<i:EventTrigger EventName="DropDownOpened">
<ei:CallMethodAction MethodName="OnSalesOrderOpenedCommand" TargetObject="{Binding DataContext, ElementName=comboBox}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>

MainPage.xaml.cs

public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();

this.DataContext = new MainPageViewModel();
}
}

MainPageViewModel.cs

public class MainPageViewModel : NotifyObject
{
private readonly SalesOrderRepository _repository;

public MainPageViewModel()
: this(new SalesOrderRepository())
{
}

public MainPageViewModel(SalesOrderRepository repository)
{
_repository = repository;

this.ActiveSalesOrderNumbers = new ObservableCollection<SalesOrder>();
}

private ObservableCollection<SalesOrder> _activeSalesOrderNumbers;
public ObservableCollection<SalesOrder> ActiveSalesOrderNumbers
{
get { return _activeSalesOrderNumbers; }
set
{
_activeSalesOrderNumbers = value;
NotifyPropertyChanged(() => ActiveSalesOrderNumbers);
}
}

public void OnSalesOrderOpenedCommand()
{
_repository.GetSalesOrderNumbers(result =>
{
this.ActiveSalesOrderNumbers.Clear();

result.ToList().ForEach(e => { this.ActiveSalesOrderNumbers.Add(e); });
});
}
}

public class SalesOrder : NotifyObject
{
private string _salesOrderNumber;
public string SalesOrderNumber
{
get { return _salesOrderNumber; }
set
{
_salesOrderNumber = value;
NotifyPropertyChanged(() => SalesOrderNumber);
}
}

private DateTime _lastModified;
public DateTime LastModified
{
get { return _lastModified; }
set
{
_lastModified = value;
NotifyPropertyChanged(() => LastModified);
}
}
}

public class SalesOrderRepository
{
public void GetSalesOrderNumbers(Action<IEnumerable<SalesOrder>> reply)
{
List<SalesOrder> orders = new List<SalesOrder>();

for (int i = 0; i < 10; i++)
{
orders.Add(new SalesOrder { SalesOrderNumber = i.ToString(), LastModified = DateTime.Now });
}

reply(orders);
}
}

通知对象.cs

public abstract class NotifyObject : INotifyPropertyChanged
{
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = delegate { };

/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected void NotifyPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);

PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);

handler(this, e);
}
}

/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="property">The property.</param>
protected void NotifyPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
{
var lambda = (LambdaExpression)property;

MemberExpression memberExpression;

if (lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else memberExpression = (MemberExpression)lambda.Body;

NotifyPropertyChanged(memberExpression.Member.Name);
}

/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
public void VerifyPropertyName(string propertyName)
{
// If you raise PropertyChanged and do not specify a property name,
// all properties on the object are considered to be changed by the binding system.
if (String.IsNullOrEmpty(propertyName))
return;

// Verify that the property name matches a real,
// public, instance property on this object.
if (this.GetType().GetProperties().Where(p => p.Name == propertyName).FirstOrDefault() == null)
{
throw new ArgumentException(String.Format("Invalid property name: {0}", propertyName));
}
}
}

关于c# - 银光 4 : How to make a combobox refresh its ItemsSource on open,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4830264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com