新建用户控件:MilutSelect
XAML:
<Grid x:Name="LayoutRoot" Background="White">
<ComboBox x:Name="chkTest" MinHeight="20"
DropDownOpened="chkTest_DropDownOpened" DropDownClosed="chkTest_DropDownClosed">
</ComboBox>
</Grid>
后台代码:
public partial class MilutSelect : UserControl
{
private string _SelectValue;
/// <summary>
/// 选择的值
/// </summary>
public string SelectValue
{
get { return _SelectValue; }
}
public MilutSelect()
{
InitializeComponent();
}
/// <summary>
/// 设置选择项
/// </summary>
/// <param name="values"></param>
public void SetSelectValue(IList<string> values)
{
CheckList.Clear();
if (values != null && values.Count > 0)
{
_SelectValue = string.Join(",", values);
if (chkTest.Items != null && chkTest.Items.Count > 0)
{
foreach (var item in chkTest.Items)
{
if (item is CheckBox)
{
var ck = item as CheckBox;
if (values.Contains(ck.Content.ToString()))
{
ck.IsChecked = true;
CheckList.Add(ck);
}
}
}
}
}
bindCalues();
}
/// <summary>
/// 数据绑定
/// </summary>
/// <param name="dataSource"></param>
public void BindDataSource(IList<string> dataSource)
{
if (dataSource != null && dataSource.Count > 0)
{
IList<ComboBoxItem> list=new List<ComboBoxItem>();
foreach (var item in dataSource)
{
var bi = new CheckBox { Content = item};
bi.Click += CheckBox_Click;
chkTest.Items.Add(bi);
}
chkTest.Items.Add(new ComboBoxItem());
}
}
private List<CheckBox> CheckList = new List<CheckBox>();
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
if ((sender as CheckBox).IsChecked == true)
{
CheckList.Add(sender as CheckBox);
}
else
{
CheckList.Remove(sender as CheckBox);
}
}
private void chkTest_DropDownOpened(object sender, EventArgs e)
{
chkTest.Items.RemoveAt(chkTest.Items.Count - 1);
}
private void chkTest_DropDownClosed(object sender, EventArgs e)
{
bindCalues();
}
private void bindCalues()
{
string name = "";
foreach (var one in CheckList)
{
name += one.Content + ",";
}
if (name.Length > 0)
name = name.Remove(name.Length - 1);
chkTest.Items.Add(new ComboBoxItem() { Content = name.ToString() });
_SelectValue = name;
chkTest.SelectedIndex = chkTest.Items.Count - 1;
}
}
调用时:
页面引用用户控件,x:name:msl
msl.BindDataSource(new List<string>(){“1”,"2","3","4","5"});//绑定数据
msBussiness.SetSelectValue((new List<string>(){“1”,"2"});设置选择项