gpt4 book ai didi

c# - 在 Blazor 中,如何在动态模型中 @bind 然后触发 @onchange

转载 作者:行者123 更新时间:2023-12-03 23:10:29 24 4
gpt4 key购买 nike

模型:

public class FiltersModel
{
public CheckBoxListWithTitle Brand { get; set; }
}

public class CheckBoxListWithTitle
{
public List<FilterCheckBox> CheckBoxes { get; set; }
}

public class FilterCheckBox
{
public string Value { get; set; }
public bool Checked { get; set; }
}
Razor :
@foreach (var item in Model.Brand.CheckBoxes)
{
<label>
@item.Value
<input type="checkbox" @onchange="@FilterChangedBrand" />
</label>
}
@代码:
public FiltersModel Model { get; set; } // Initialized in OnParametersSet

private void FilterChangedBrand(UIChangeEventArgs e)
{
string newCheckedBrand = e.Value.ToString();
// Now How to Find and Set the relevant Model property to newCheckedBrand
FiltersChanged?.Invoke(Model);
}
如何在 FilterChangedBrand 方法中查找相关的 Model 属性并将其设置为 newCheckedBrand。
或者在复选框标记中使用 @bind="@item.Checked"然后在复选框之一的选中状态发生变化时引发事件?

最佳答案

由于无法使用 @bind 和 @onchange,因此您必须完全在代码中进行更改。最简单的方法是使用 lambda 来捕获 item
Razor

@foreach (var item in Model.Brand.CheckBoxes)
{
<label>
@item.Value
<input type="checkbox" @onchange="(e) => FilterChangedBrand(item, e)" />
</label>
}

@代码
public FiltersModel Model { get; set; } // Initialized in OnParametersSet

public event Action<FiltersModel> FiltersChanged;

private void FilterChangedBrand(FilterCheckBox item, ChangeEventArgs e)
{
// here you do work of @bind
item.Checked = !item.Checked;
string newCheckedBrand = e.Value.ToString();
// Now How to Find and Set the relevant Model property to newCheckedBrand
FiltersChanged?.Invoke(Model);
}

另一种更复杂的方法,如果你想重用你的 UI,例如 WPF 是将事件级联放在模型本身中,这可能会有所帮助。
public class CheckBoxListWithTitle
{
private List<FilterCheckBox> items = new List<FilterCheckBox>();
public IReadOnlyList<FilterCheckBox> CheckBoxes => items.AsReadOnly();

public event EventHandler ModelChanged;

public void Add(FilterCheckBox item)
{
item.CheckedChanged += this.Item_CheckedChanged;
this.items.Add(item);
}

private void Item_CheckedChanged(object sender, EventArgs e)
{
ModelChanged.Invoke(this, EventArgs.Empty);
}
}

public class FilterCheckBox
{
public string Value { get; set; }
public bool Checked { get; set; }

public event EventHandler CheckedChanged;
}

如你所见 CheckBoxListWithTitle将处理所需事件的传播。在 Razor 中,您只订阅 CheckBoxListWithTitle.ModelChanged

关于c# - 在 Blazor 中,如何在动态模型中 @bind 然后触发 @onchange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com