首页 > 解决方案 > 如何将在 c# 代码中生成的字符串插入 xaml 按钮?

问题描述

我正在尝试创建一个离线密码管理器。有一个函数应该生成一个密码并将其放入应该保存该数据的条目中。现在我正在努力将 C# 代码生成方法的结果插入到 xaml 按钮中。

我尝试在 C# 代码中创建一个条目,并为其分配一个文本属性。第一件事是我不确定这是否是正确的方法。第二件事是我不知道我还能做些什么来解决这个问题。

//this is the generating button in app
void OnGenerateClicked(object sender, EventArgs e)
{
    var passwordEntry = new Entry();
    passwordEntry.SetBinding(Entry.TextProperty, "Haslo");

    bool includeLowercase = true;
    bool includeUppercase = true;
    bool includeNumeric = true;
    bool includeSpecial = true;
    bool includeSpaces = false;
    int lengthOfPassword = 12;
    string password = 
        PasswordGeneration.GeneratePassword(includeLowercase, includeUppercase, 
        includeNumeric, includeSpecial, includeSpaces, lengthOfPassword);
    var Haslo = new Entry { Text = password }; 
    // here i've tried to assign the text property to the entry 
    //  "Haslo" but unfortunately it's not working.
}

XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="OpassV1.Widoki.ServicePage">
    <StackLayout Margin="20" VerticalOptions="StartAndExpand">
        <Label Text="Nazwa" />
        <Entry Text="{Binding Nazwa}" /> 
        <Label Text="Hasło"/>
        <Entry x:Name="Haslo" Text="{Binding Haslo}"/>
        <Button Text="Genruj hasło" Clicked="OnGenerateClicked" /> 
        <Button Text="Zapisz" Clicked="OnSaveClicked" />
        <Button Text="Usuń" Clicked="OnDeleteClicked" />
        <Button Text="Anuluj" Clicked="OnCancelClicked" />
        </StackLayout>
</ContentPage>

单击生成按钮“OnGenerateClicked”后,我想在“Binding Nazwa”条目中显示生成的密码

我很感激所有的答案:)

标签: c#xamlxamarin

解决方案


这会创建一个新的 entry 实例

var Haslo = new Entry { Text = password }; 

您想使用您在 XAML 中创建的现有 Entry 实例。XAML 中具有x:Name属性的任何元素都应该可以通过代码隐藏中的名称访问

Haslo.Text = password;

推荐阅读