UWP привязан, флажок отмечен? - PullRequest
0 голосов
/ 15 мая 2018

Итак, я создал комбинированный список с несколькими флажками. Мой xaml выглядит так:

<ComboBox x:Name="CbSandwichFilling" ItemsSource="{x:Bind SandwichFillingList}" PlaceholderText="Choose sandwich filling">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Name="{Binding Ingredient_name}" Content="{Binding Ingredient_name}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Мой C # выглядит так:

private List<Ingredients> sandwichFilling;

public List<Ingredients> SandwichFillingList
{
    get { return sandwichFilling; }
    set { sandwichFilling = value; }
}

public BasicSandwiches()
{
    sandwichFilling = Ingredients.GetIngredients("sandwichFilling");
    this.DataContext = SandwichFillingList;
}

Функция GetIngredients ("sandwichFilling") получает сэндвич-наполнения из базы данных и помещает их в флажок внутри ComboBox.

Когда пользователь нажимает кнопку, я хочу, чтобы программа знала, какие флажки отмечены. Как я могу это сделать?

1 Ответ

0 голосов
/ 18 мая 2018

Когда пользователь нажимает кнопку, я хочу, чтобы программа знала, какие флажки отмечены.Как я могу это сделать?

Для вашего требования вам нужно создать источник данных для привязки.Ниже приведена модель данных, которая наследует интерфейс INotifyPropertyChanged.

public class Ingredients : INotifyPropertyChanged
{
    public Ingredients()
    {

    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChang([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    private string _Ingredient_name;
    public string Ingredient_name
    {
        get
        {
            return _Ingredient_name;
        }
        set
        {
            _Ingredient_name = value;
            OnPropertyChang();
        }
    }

    private bool _IsCheck;
    public bool IsCheck
    {
        get
        {
            return _IsCheck;
        }
        set
        {
            _IsCheck = value;
            OnPropertyChang();
        }
    }
}

Затем создайте MainPageViewModel, который будет использоваться для связывания с кодом xaml.

public class MainPageViewModel
{
    public ObservableCollection<Ingredients> Items { get; set; }
    public MainPageViewModel()
    {
        Items = new ObservableCollection<Ingredients>()
        {
            new Ingredients()
            {
                Ingredient_name= "Nico",
                IsCheck=false
            },
               new Ingredients()
            {
                Ingredient_name= "mimi",
                IsCheck=false
            },
                  new Ingredients()
            {
                Ingredient_name= "kiki",
                IsCheck=false
            },
                     new Ingredients()
            {
                Ingredient_name= "zizi",
                IsCheck=false
            },
                        new Ingredients()
            {
                Ingredient_name= "sasa",
                IsCheck=false
            },

        };

    }
}

Использование

<Page.DataContext>
    <local:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="4*"/>
        <RowDefinition Height="1*"/>

        <RowDefinition Height="4*"/>
    </Grid.RowDefinitions>
    <ComboBox  x:Name="CbSandwichFilling" ItemsSource="{Binding Items}" PlaceholderText="Choose sandwich filling">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Ingredient_name}" IsChecked="{Binding IsCheck,Mode=TwoWay}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    <Button Grid.Row="1" Click="Button_Click" Content="ShowAllItem"/>
    <TextBlock Grid.Row="2" Name="InfoDisplay" />
</Grid>

Обратите внимание, что необходимо установить режим привязки свойства IsChecked как TwoWay, чтобы он мог изменять источник данных при проверке.И вы не можете связать свойство Name с Ingredient_name, иначе оно выдаст исключение xaml.

MainPage.cs

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        StringBuilder info = new StringBuilder();
        foreach (var item in ViewModel.Items )
        {
            info.AppendLine(item.Ingredient_name + "--------" + item.IsCheck.ToString());
        }
        InfoDisplay.Text = info.ToString();
    }
}

enter image description here

Для получения дополнительной информации вы можете обратиться Data binding in depth документ.

...