【问题标题】:Button doesn't Enable after IsEnabled Binding updatesIsEnabled 绑定更新后按钮未启用
【发布时间】:2015-12-10 04:45:54
【问题描述】:

我有一个名为 Document

的类
public class Document : INotifyPropertyChanged
{                  
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }             

    private string oldId;
    public string OldId
    {
        get { return oldId; }
        set { id = value; }
    }

    private string id;
    public string Id
    {
        get { return id; }
        set { 
            id = value;
            NotifyPropertyChanged("HasChanged");
        }
    }

    private string path;
    public string Path
    {
        get { return path; }
        set { path = value; }
    }

    public bool HasChanged
    {
        get { return id != oldId; }
    }

    public Document(string id, string path)
    {
        this.id = id;
        this.oldId = id;
        this.path = path;
    }
}

我在我的 WPF 代码后面有一个 Documents 列表,items 是我表单中的一个 ItemsControl。

AddItem("a", "b");
AddItem("b", "b");
AddItem("c", "b");
AddItem("d", "b");

...

private void AddItem(string key, string value)
{
    items.Items.Add(new Document(key, value));
}

我的 WPF 如下所示:

<ItemsControl x:Name="items" AlternationCount="100">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="8*"/>
                    <ColumnDefinition Width="auto"/>
                </Grid.ColumnDefinitions>

                <TextBox 
                    Text="{Binding Id}"

                    PreviewKeyDown="TextBox_PreviewKeyDown"></TextBox>
                <Button 
                    Grid.Column="1" 

                    IsEnabled="{Binding HasChanged}"
                    Content="Ok"

                    Click="ButtonOk_Click"></Button>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

如您所料,当 tb 中的文本与原始文本不同时,我想启用 Button。

问题是在我更改其中一个文本框中的文本后,按钮无法启用。

如果我点击按钮,它会变为启用。

如果我再次单击它,它会执行 OnClick。

有什么改变,按钮在按键时更新?

请记住,我使用 ItemControl 即时生成按钮,因此无法通过其名称从代码隐藏更新它。

我不使用 ViewModel,也不想添加,因为这个项目太小,无法使用任何基于 ViewModel 的设计模式。

【问题讨论】:

    标签: c# wpf button binding


    【解决方案1】:

    您遇到的可能是因为 TextBoxes 的 Text 属性的默认绑定具有 UpdateSourceTrigger=LostFocus

    这意味着在TextBox 失去键盘焦点(当您单击禁用按钮时)之前,您的Id 属性不会被更新。可能,如果您单击另一个 TextBox,按钮将同样启用。

    您可以在 XAML 中更改此行为,如下所示:

    <TextBox Text="{Binding Id, UpdateSourceTrigger=PropertyChanged}"
             PreviewKeyDown="TextBox_PreviewKeyDown"></TextBox>
    

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2021-11-02
      • 1970-01-01
      • 2018-01-21
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      相关资源
      最近更新 更多