【发布时间】:2017-07-12 04:49:57
【问题描述】:
我有一个 comboBox,其值为 [day,weeks,months,years]
<ComboBox Width="130" Margin="0,10,0,16" ItemsSource="{Binding PeriodCollection }"
SelectedItem="{Binding SelectedDuration }"
Text="" DisplayMemberPath="Name" />
在 comboBox 旁边,我有一个文本框。如果用户从组合框中选择“周”并将值 2 放入文本框中,则在数据库中我必须保存 2*7 = 14 [天]。
为了实现这个功能,我创建了周期集合。
public class Period : BaseObject
{
private string name;
public string Name
{
get { return name; }
set { name = value; NotifyPropertyChanged(); }
}
private int numberOfDays;
/// <summary>
/// number of days in period
/// </summary>
public int NumberOfDays
{
get { return numberOfDays; }
set { numberOfDays = value; NotifyPropertyChanged(); }
}
public Period(string perdioName, int numberOfDayInPeriod)
{
Name = perdioName;
NumberOfDays = numberOfDayInPeriod;
}
}
}
public static class PeriodManager
{
private static ObservableImmutableList<Period> periodCollection;
/// <summary>
/// return a collection of time period in days ///
/// </summary>
/// <returns>Days, Week,Month, year</returns>
public static ObservableImmutableList<Period> GetPeriodCollection()
{
if (periodCollection == null)
{
periodCollection = new ObservableImmutable.ObservableImmutableList<Entities.Period>();
periodCollection.Add(new Period("Days", 1));
periodCollection.Add(new Period("Week", 7));
periodCollection.Add(new Period("Month", 30));
periodCollection.Add(new Period("Year", 365));
}
return periodCollection;
}
/// you can create method can return a period from a day number...
}
现在在我的 viewModel 中,我正在尝试实现一个返回天数的方法。
private ObservableImmutableList<Period> periodCollection;
public ObservableImmutableList<Period> PeriodCollection { get { return periodCollection; } set { periodCollection = value; NotifyPropertyChanged(); } }
private Period selectedDuration;
public Period SelectedDuration { get { return selectedDuration; } set { selectedDuration = value; NotifyPropertyChanged(); } }
private void GetPeriod()
{
PeriodCollection = PeriodManager.GetPeriodCollection();
//here I need to write logic to merge from both values [ txtBox+combox]
}
但我对 -
感到困惑在保存如何将文本框值与组合框天的返回值合并时[如果在文本框中输入 2 并在组合框中选择周,我需要值 14]
请在 wpf mvvm 概念中帮助我。我在 web 中尝试过,但在 mvvm 中找不到任何内容。
【问题讨论】:
-
如果您绑定到
ItemsSource,则无需在xaml 中添加ComboBoxItems。在 MVVM 中,您通常会在 ViewModel/Model 中定义所有集合,并且视图只需绑定到它们。 -
itemsource code 现在是空白的“_Collection”我需要完整的解决方案,什么逻辑最适合这个。
-
WPF ComboBox binding ItemsSource 的可能重复项。有关
ComboBox.ItemsSource绑定的示例,请参阅接受的答案。或者,也许你想bind to static property。 -
itemsource 已编辑,检查。这从来都不是我的问题。问题在于合并值和保存。
-
您可以将
TextBox.Text绑定到double Number属性,将ComboBox.SelectedItem绑定到Period SelectedPeriod属性。然后你需要一个命令(或者简单地从这些属性的设置器中调用一些方法):在这个命令中做Number * SelectedPeriod.NumberOfDays.