简体   繁体   中英

Issue binding a boolean to the IsEnabled of a button

I found some questions that went into the same direction, but could find any that fit into my problem directly.

I have a list in a list to have a 2D array of buttons. Now I want to bind the "IsEnabled" state to the property of a class. The "Tag" is already getting filled with the correct values from the objects of that class but the "IsEnabled" won't work whatever I try.

Here's my XAML for the DataTemplate I'm using:

    <DataTemplate x:Key="DataTemplate_Level2">
        <Button Height="35" Width="35" Margin="-1,-1,-1,-1" IsEnabled="{Binding hit}" x:Name="fieldButton" Click="fieldClick" Tag="{Binding}" Style="{StaticResource ButtonStyle1}"/>
    </DataTemplate>

    <DataTemplate x:Key="DataTemplate_Level1">
        <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DataTemplate>

Here is the code that fills the lists:

fields=new List<List<Field>>();

for(int i = 0; i < SIZE; i++) {
    fields.Add(new List<Field>());
    for(int j = 0; j < SIZE; j++) {
        fields[i].Add(new Field(i, j));
    }
}

This is the class that I want the "hit" property to bind to the "IsEnabled": private int x; private int y;

    public Boolean hit;

    public int X { get => this.x; set => this.x = value; }
    public int Y { get => this.y; set => this.y = value; }

    public Field(int x,int y) {
        this.x = x;
        this.y = y;
        this.hit = false;
    }

    public override string ToString() {
        return this.x + "," + this.y;
    }

hit is a field in your code. You can only bind to a property.

Try changing it to a property like this:

public bool hit { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM