RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-502713

emokid.'s questions

Martin Hope
ikikaidesu
Asked: 2024-07-07 19:00:49 +0000 UTC

c# WPF 随着时间的推移改变窗口中的内容并传输数据

  • 5

我想知道如何在代码中更改一段时间后窗口中的内容?按照惯例,有Main一个页面,我想将其更改为Additional我在代码中运行的计时器结束时的页面。有一些想法可以通过ContentControl我简单地存储当前视图并在计时器结束时将其更改为Additional,但我还需要Main将数据从零件传输到Additional,这里出现了第二个问题:我可以MainVM存储两者的模型吗交互页面,或者相反,Model为两者创建一个页面VM。我确信这两种方法都不是很好,所以我想知道是否有更好的方法来实现这一点?

c#
  • 1 个回答
  • 56 Views
Martin Hope
ikikaidesu
Asked: 2024-07-06 03:38:52 +0000 UTC

c# wpf 检查当前行的最后一个单词

  • 5

我正在创建一个粗略的页面来检查输入是否正确。关键是你输入文本,如果它与原始文本匹配,那么你的字符是白色的,否则是红色的。问题是我使用textblockc来显示文本textwrapping,如果单词不适合,则会将其转移到新行,但是当输入我的单词时,一半保留在同一行,一半保留在新行(由于wrappanel),并且我需要正确的传输,而发生这种情况是因为我以某种方式注意到该人输入了当前行的最后一个单词,然后会从文本中删除该行,但我不知道该怎么做,我附上问题的代码和截图如下:

截屏: 在此输入图像描述

正如你在这里看到的,这个词bloomed一半在上面,一点在下面。为了防止这种情况,我想以某种方式捕获一个人输入了当前行的最后一个单词(如示例中所示freshly)的事实,然后通过删除当前行并在集合中清除它来更新文本。

查看代码:

<Grid Background="#282a36">
    <TextBlock Text="{Binding OriginalText}"
               FontFamily="Consolas"
               Foreground="Gray" 
               FontSize="16" 
               IsHitTestVisible="False"
               TextWrapping="Wrap"/>
    <TextBox Text="{Binding UserInput, UpdateSourceTrigger=PropertyChanged}" 
             FontSize="16" 
             FontFamily="Consolas"
             Background="Transparent" 
             Foreground="Transparent" 
             BorderBrush="Transparent"
             TextWrapping="Wrap"/>
    <ItemsControl ItemsSource="{Binding ColoredUserInput}" VerticalAlignment="Top">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Character}" 
                           Foreground="{Binding Color}" 
                           FontSize="16"
                           FontFamily="Consolas"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

视图模型代码:

public class MainViewModel : INotifyPropertyChanged
{
    private string _originalText = "The curious cat explored every corner of the garden, chasing butterflies and sniffing at freshly bloomed flowers. Meanwhile, the old oak tree stood tall, its branches swaying gently in the summer breeze. Birds chirped happily overhead, creating a symphony of natural sounds. The sun painted the sky in shades of orange and pink as evening approached.";
    private string _userInput;
    private ObservableCollection<ColoredCharacter> _coloredUserInput;

    public MainViewModel()
    {
        ColoredUserInput = new ObservableCollection<ColoredCharacter>();
    }

    public string OriginalText
    {
        get => _originalText;
        set
        {
            _originalText = value;
            OnPropertyChanged();
        }
    }

    public string UserInput
    {
        get => _userInput;
        set
        {
            _userInput = value;
            OnPropertyChanged();
            UpdateColoredUserInput();
        }
    }

    public ObservableCollection<ColoredCharacter> ColoredUserInput
    {
        get => _coloredUserInput;
        set
        {
            _coloredUserInput = value;
            OnPropertyChanged();
        }
    }

    private void UpdateColoredUserInput()
    {
        ColoredUserInput.Clear();
        for (int i = 0; i < OriginalText.Length; i++)
        {
            if (i < UserInput.Length)
            {
                var character = OriginalText[i];
                var color = UserInput[i] == character ? Brushes.White : Brushes.Red;
                ColoredUserInput.Add(new ColoredCharacter { Character = character.ToString(), Color = color });
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class ColoredCharacter
{
    public string Character { get; set; }
    public Brush Color { get; set; }
}

因为我上面说过页面是原始的(它仅用于创建我将来要传输到项目的内容),那么这不是我在大多数情况下了解的纯代码,但如果这里有一些非常糟糕的东西,我会很高兴知道!

更新:根据我的想法,我自己将通过该方法在文本中创建连字符,并简单地UpdateColoredUserInput检查下一个字符是否存在并且等于\n,然后删除当前行,但是出现了新问题创建此方法是因为\n需要插入这些方法来检查它是否能按字符将新单词放入当前行(这里您需要弄清楚如何根据字体大小和宽度进行计算,textblock一般来说这听起来不像一个非常好的方法,但至少它看起来有点不像神奇地(或通过formattedtext)找出这个词是否适合的方法)。

c#
  • 2 个回答
  • 50 Views
Martin Hope
ikikaidesu
Asked: 2024-06-07 21:23:15 +0000 UTC

如何通过视图更新WPF MVVM中的数据?

  • 5

我有textbox

            <TextBox Text="{Binding DisplayNickName}"
                     Style="{StaticResource enternickname}"
                     Margin="10,10,0,0"/>

他的风格中有一个按钮。我希望当我单击用户的昵称时,在文件和模型中更新用户的昵称,但我不知道该怎么做。尝试解决我添加到Model方法中的问题

public void update_nick(string nickname)
        {
            // обновляем в файле
            JsonData.set_name(nickname);
            // устанавливаем ник в model
            this.nickname = nickname;
        }

之后我想在虚拟机中发出命令,但不幸的是我不知道传入数据到底要采取什么(联系什么来获取它)并且我现在陷入了这一点,所以我希望更有经验的人提供帮助,我到底应该在VM中联系什么才能将数据输入到文本框中(我的想法是DisplayNickName)以及如何在样式中指定命令?一种风格

<!--Добавим текст бокс-->
<TextBox 
    Text="{TemplateBinding Text}"
    Background="Transparent"
    BorderThickness="0"
    Foreground="#deddd0"
    FontSize="20"
    Margin="1,0,0,0"
    x:Name="NameBox"
    MaxLength="15"
    Width="auto"/>
<!--Кнопка подтвеждения никнейма-->
<Button VerticalAlignment="Center"
        HorizontalAlignment="Right"
        Background="Transparent"
        BorderThickness="0"
        Cursor="Hand"
        Command="{Binding DataContext.UpdateNicknameCommand, RelativeSource={RelativeSource AncestorType=Window}}"
        CommandParameter="{Binding Text, ElementName=NameBox}">
    <Image Source="/images/check_mark.png" Width="25" Height="25"/>
    <!--Добавил в стиль кнопки триггеры для того чтобы она выводилась только при вводе и чтобы фон не менялся-->
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Visibility" Value="Collapsed"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="Border" Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Border>
                        <ControlTemplate.Triggers>
                            <DataTrigger Binding="{Binding IsKeyboardFocused, ElementName=NameBox}" Value="True">
                                <Setter Property="Visibility" Value="Visible"/>
                            </DataTrigger>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="Transparent" TargetName="Border" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

更改昵称的命令及命令方法

public ICommand ChangeNickNameCommand { get; set; }
private void ChangeNickName(object obj)
{
    if (obj is string nickname)
    {
        _accountModel.update_nick(nickname);
    }
}

来自带有绑定的构造函数的一段代码

    // привязываем команду
    ChangeNickNameCommand = new RelayCommand(ChangeNickName);

I命令码

class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
    public void Execute(object parameter) => _execute(parameter);
}
c#
  • 1 个回答
  • 37 Views
Martin Hope
ikikaidesu
Asked: 2024-06-05 05:18:26 +0000 UTC

如何在 MVVM 架构中正确地将数据从模型传输到视图并返回,以及在 ViewModel 中该怎么做?

  • 6

我想问一些我找不到答案的问题(可能是我看起来很糟糕):

  1. 如何使用 sql/文件中的数据填充模型(在初始化窗口之前,创建模型的实例并在那里插入数据或其他内容?)
  2. 如何更改模型数据并写入它?(更准确地说,我可以在哪里更改ViewModel中的数据并调用更新sql/文件中数据的方法?)
  3. 如何从视图中获取数据并将其传递给 ViewModel 或 Model?(通过访问元素将其传递给 ViewModel 并使用方法将其传递给 Model 或者还有其他更正确的方法吗?)
c#
  • 1 个回答
  • 62 Views
Martin Hope
ikikaidesu
Asked: 2024-01-29 23:34:39 +0000 UTC

python pdf文件读取错误

  • 5

我正在编写读取 pdf 文件并将其转换为 DataFrame 的代码。

table = tabula.read_pdf(pdf_schedule, pages='all', multiple_tables=True, lattice=True)

问题是,在我传入的文件中,有时左侧的第一个元素没有边,导致表格具有 NaN 而不是该单元格的数据。该怎么办?
这是所有代码

columns = table[0].columns
# Создание списка строк
rows_list = []
for t in table:
    for _, row in t.iterrows():
        rows_list.append(row)
# Создание DataFrame из списка строк с явным указанием столбцов
df = pd.DataFrame(rows_list, columns=columns)

这是表格行的第一个元素不正确的示例的屏幕截图

在此输入图像描述

python
  • 1 个回答
  • 32 Views
Martin Hope
ikikaidesu
Asked: 2024-01-22 01:08:05 +0000 UTC

python telebot无法检查频道订阅

  • 5

我正在用 python telebot 编写一个电报机器人,我编写了一个代码来检查一个人的频道订阅,该机器人是频道的所有者,它拥有所有权利,要检查的用户已经订阅了该频道。

@bot.callback_query_handler(func=lambda call: call.data in ['subscribe_to_channel'])
def process_subscribe_to_channel(call):
    """функция обрабатывающая кнопку подписаться при выводе стартового сообщения"""
    user = bot.get_chat_member(channel_id, call.from_user.id)
    if user and user.status in ['creator', 'administrator', 'member']:
        bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id, reply_markup=None)
        select_role(call.message)
    else:
        bot.send_message(call.from_user.id, "Вы не подписались!")

由于某种原因,它在 user_id 上出现错误(对 Telegram API 的请求不成功。错误代码:400。描述:错误请求:找不到用户)。作为channel_id,我插入了从 getIDs 机器人收到的带减号的 ID,以及字符串格式的频道用户名 (@channelname),没有任何帮助。

python
  • 1 个回答
  • 31 Views
Martin Hope
emokid.
Asked: 2022-07-28 23:50:58 +0000 UTC

Python解析野莓

  • 0

我正在学习从网站收集数据。决定用野莓。我无法从网站上获取新旧价格,文件中只有 None 或 []。最有可能的问题是我选错了课,但我就是不知道该选哪门课。我参加了所有有价格的课程。这是产品的链接https://www.wildberries.ru/catalog/37115463/detail.aspx?targetUrl=GP。

import os
import requests
from bs4 import BeautifulSoup

try:
    os.mkdir(r'') # тут путь к диску
except FileExistsError:
    print('Файл уже существует') # создание папки

def infotovar(url):
    file = open("info.txt", 'w+')  # создание файла в котором будет все информация о товаре(1 фото, старая и новая цена, цвет, бренд и тип)
    pathtofile = os.path.abspath('info.txt')  # путь к файлу
    api = requests.get(url)
    result = api.content
    soup = BeautifulSoup(result, 'html.parser')
    price = soup.find('span', class_='price-block__price-wrap').get_text(strip=True)
    print(price)
    file.close()
    os.replace(pathtofile, 'C:\') # перемещение файла в папку

def main():
    infotovar('https://www.wildberries.ru/catalog/37115463/detail.aspx?targetUrl=GP')

if __name__ == "__main__":
    main()
python парсер
  • 1 个回答
  • 1161 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5