ArKTS: staic message simple UI

项目结构:

一种:

/**
 # encoding: utf-8
 # 版权所有 2024 ©涂聚文有限公司
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-arkui-advanced-dialog
 # Author    : geovindu,Geovin Du 涂聚文. https://yesicon.app/
 # IDE       : DevEco Studio 5.1.1 HarmonyOS ArKTS
 # OS        : windows 10  ohpm install @coremail/mail_base     https://gitee.com/openharmony-tpc/ohos_mail_base
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2024/10/31 20:33
 # User      : geovindu
 # Product   : MyApplicatin
 # Project   : MyApplicatin
 # File      : WxList.ets
 * */
import { UserInfoBase } from '../../constant/UserInfoBase'
import { router } from '@kit.ArkUI';
import { TodoTitleNameUtils } from '../../pages/utils/TodoTitleNameUtils'
import { trustedAppService } from '@kit.DeviceSecurityKit';
import { CommonConstantWX } from '../../constant/CommonConstantWX'
import { UserMessageBase } from '../../constant/UserMessageBase';
 
// 2. 定义传递的参数类型(包含user属性)
interface UserParams {
  user: UserInfoBase;
}
 
@Entry
@Component
struct WxList {
  @State message: string = '聊天';
  @State users: UserInfoBase=new UserInfoBase() ;
  @State messagelist: Array<UserMessageBase> = CommonConstantWX.mUserMessage
  // 3. 获取参数并断言为UserParams类型
  //const params = router.getParams() as UserParams | undefined;
 
  aboutToAppear() {
    // 获取传递的参数
    const params =router.getParams() as UserParams | undefined;// router.getParams();
    if (params?.user) {
      this.users = params.user as UserInfoBase; // 类型转换,确保与传递的item结构一致
 
    }
  }
  build() {
    Column() {
 
      Row() {
        TodoTitleNameUtils({ isTitle: true, titleName: this.users.name === undefined ? "" : this.users.name })
      }
      .width('100%')
      .height('15pv')
 
      List() {
        ForEach(this.messagelist, (item: UserMessageBase) => {
          ListItem() {
            Column() {
              // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
              Row() {
                if(item.category===0) {
                  Image(item.img)
                    .width(40)
                    .height(50)
                    .margin({right: 8})
                    .borderRadius(5)
                    .objectFit(ImageFit.Contain)
                  // 移除不必要的align,由外层Row统一控制对齐
                }
                Text(item.content)
                  .fontSize($r('app.float.pagemessagesize'))
                  .fontWeight(FontWeight.Bold)
                  .backgroundColor(item.category===0?'#ffffff': '#ff81cd0a') // 白色背景
                  .borderRadius(10) // 圆角效果,数值可调整
                  .padding({ left: 12, right: 12, top: 8, bottom: 8 }) // 文本与背景的内边距
                  .margin({ right: 8 }) // 图片与文本之间的间距
                  .onClick(() => {
                    router.pushUrl({
                      url: 'pages/weixin/WXHome',
                    })
                  })
                if(item.category===1) {
                  Image(item.img)
                    .width(40)
                    .height(50)
                  .margin({left: 8})
                    .borderRadius(5)
                    .objectFit(ImageFit.Contain)
                  // 移除不必要的align,由外层Row统一控制对齐
                }
              }
              .width('100%')
              .justifyContent(item.category===0?FlexAlign.Start:FlexAlign.End) // 关键:Row内元素靠右排列 FlexAlign.End
              .align(item.category===0?Alignment.Start:Alignment.End) // Alignment.End
              .margin({ right: 1})
            }
            .alignItems(item.category===0?HorizontalAlign.Start:HorizontalAlign.End) // 确保Column的子元素(Row)靠右对齐 HorizontalAlign.End
            .align(item.category===0?Alignment.Start:Alignment.End) //Alignment.End
            // 可根据需要添加整体外边距
            .margin({ right: 12, top: 8, bottom: 8 })
 
 
 
          }.align(item.category===0?Alignment.Start:Alignment.End) // Alignment.End
        })
      }.height('80%')
      .width('100%')
      .backgroundColor('#ccc')
      .scrollSnapAlign(ScrollSnapAlign.START)
 
      Row({ space: 8 }) {
        // 语音按钮
        Image($r('app.media.SoundHighSolid'))
          .width(30)
          .height(30)
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            router.pushUrl({
              url: 'pages/weixin/WXHome',
            })
          })
 
        // 输入框
        TextInput({ placeholder: '请输入消息...'})
          .id('WxListHelloWorld')
          .fontSize($r('app.float.page_text_font_size'))
          .fontWeight(FontWeight.Normal)
          .backgroundColor('#ffffff')
          .borderRadius(20)  // 圆角输入框
          .padding({ left: 16, right: 16 })  // 文本内边距
          .onClick(() => {
            this.message = this.users?.name || "";
          })
          .flexGrow(1)  // 自动填充剩余空间
          .width('75%')
        // 发送按钮
        Button('+')
          .fontSize(18)
          .width(40)
          .height(40)
          .borderRadius(20)  // 圆形按钮
          .backgroundColor('#07C160')  // 微信绿
          //.textStyle({ color: '#ffffff' })
          .onClick(() => {
            router.back()
          })
      }
      .margin({ top: 8, left: 12, right: 12, bottom: 8 })  // 整体外边距
      .height(50)  // 合适的高度
      .backgroundColor('#f5f5f5')  // 浅灰背景
      .alignItems(VerticalAlign.Center)  // 垂直居中对齐
      .width('100%')
    }
  }
}

二种:

/**
 # encoding: utf-8
 # 版权所有  2025 ©涂聚文有限公司™ ®
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述:
 # Author    : geovindu,Geovin Du 涂聚文.
 # IDE       : DevEco Studio 5.1.1  HarmonyOS ArKTS
 # os        : windows 10
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2025/8/2 23:56
 # User      :  geovindu
 # Product   : DevEco Studio
 # Project   : SQLiteApp
 # File      : WxControl.ets
 **/
import { UserMessageBase } from '../constant/UserMessageBase';
import { router } from '@kit.ArkUI';

@Component//表示组件
export default struct WxControl {

  @Prop useritem:UserMessageBase=new UserMessageBase

  build() {

    // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
    Row() {
      if(this.useritem.category===0) {
        Image(this.useritem.img)
          .width(40)
          .height(50)
          .margin({right: 8})
          .borderRadius(5)
          .objectFit(ImageFit.Contain)
        // 移除不必要的align,由外层Row统一控制对齐
      }
      Text(this.useritem.content)
        .fontSize($r('app.float.pagemessagesize'))
        .fontWeight(FontWeight.Bold)
        .backgroundColor(this.useritem.category===0?'#ffffff': '#ff81cd0a') // 白色背景
        .borderRadius(10) // 圆角效果,数值可调整
        .padding({ left: 12, right: 12, top: 8, bottom: 8 }) // 文本与背景的内边距
        .margin({ right: 8 }) // 图片与文本之间的间距
        .onClick(() => {
          router.pushUrl({
            url: 'pages/weixin/WXHome',
          })
        })
      if(this.useritem.category===1) {
        Image(this.useritem.img)
          .width(40)
          .height(50)
          .margin({left: 8})
          .borderRadius(5)
          .objectFit(ImageFit.Contain)
        // 移除不必要的align,由外层Row统一控制对齐
      }
    }
    .width('100%')
    .justifyContent(this.useritem.category===0?FlexAlign.Start:FlexAlign.End) // 关键:Row内元素靠右排列 FlexAlign.End
    .align(this.useritem.category===0?Alignment.Start:Alignment.End) // Alignment.End
    .margin({ right: 1})

  }

}


/**
 # encoding: utf-8
 # 版权所有 2024 ©涂聚文有限公司
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-arkui-advanced-dialog
 # Author    : geovindu,Geovin Du 涂聚文. https://yesicon.app/
 # IDE       : DevEco Studio 5.1.1 HarmonyOS ArKTS
 # OS        : windows 10  ohpm install @coremail/mail_base     https://gitee.com/openharmony-tpc/ohos_mail_base
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2024/10/31 20:33
 # User      : geovindu
 # Product   : MyApplicatin
 # Project   : MyApplicatin
 # File      : WxList.ets
 * */
import { UserInfoBase } from '../../constant/UserInfoBase'
import { router } from '@kit.ArkUI';
import { TodoTitleNameUtils } from '../../pages/utils/TodoTitleNameUtils'
import { trustedAppService } from '@kit.DeviceSecurityKit';
import { CommonConstantWX } from '../../constant/CommonConstantWX'
import { UserMessageBase } from '../../constant/UserMessageBase';
import WxControl, {  } from '../../Control/WxControl'
import { it } from '@ohos/hypium';

// 2. 定义传递的参数类型(包含user属性)
interface UserParams {
  user: UserInfoBase;
}

@Entry
@Component
struct WxList {
  @State message: string = '聊天';
  @State users: UserInfoBase=new UserInfoBase() ;
  @State messagelist: Array<UserMessageBase> = CommonConstantWX.mUserMessage
  // 3. 获取参数并断言为UserParams类型
  //const params = router.getParams() as UserParams | undefined;

  aboutToAppear() {
    // 获取传递的参数
    const params =router.getParams() as UserParams | undefined;// router.getParams();
    if (params?.user) {
      this.users = params.user as UserInfoBase; // 类型转换,确保与传递的item结构一致

    }
  }
  build() {
    Column() {

      Row() {
        TodoTitleNameUtils({ isTitle: true, titleName: this.users.name === undefined ? "" : this.users.name })
      }
      .width('100%')
      .height('15pv')

      List() {
        ForEach(this.messagelist, (item: UserMessageBase) => {
          ListItem() {
            Column() {
              // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
              WxControl({ useritem: item }) //引用用户控件
            }
            .alignItems(item.category===0?HorizontalAlign.Start:HorizontalAlign.End) // 确保Column的子元素(Row)靠右对齐 HorizontalAlign.End
            .align(item.category===0?Alignment.Start:Alignment.End) //Alignment.End
            // 可根据需要添加整体外边距
            .margin({ right: 12, top: 8, bottom: 8 })



          }.align(item.category===0?Alignment.Start:Alignment.End) // Alignment.End
        })
      }.height('80%')
      .width('100%')
      .backgroundColor('#ccc')
      .scrollSnapAlign(ScrollSnapAlign.START)

      Row({ space: 8 }) {
        // 语音按钮
        Image($r('app.media.SoundHighSolid'))
          .width(30)
          .height(30)
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            router.pushUrl({
              url: 'pages/weixin/WXHome',
            })
          })

        // 输入框
        TextInput({ placeholder: '请输入消息...'})
          .id('WxListHelloWorld')
          .fontSize($r('app.float.page_text_font_size'))
          .fontWeight(FontWeight.Normal)
          .backgroundColor('#ffffff')
          .borderRadius(20)  // 圆角输入框
          .padding({ left: 16, right: 16 })  // 文本内边距
          .onClick(() => {
            this.message = this.users?.name || "";
          })
          .flexGrow(1)  // 自动填充剩余空间
          .width('75%')
        // 发送按钮
        Button('+')
          .fontSize(18)
          .width(40)
          .height(40)
          .borderRadius(20)  // 圆形按钮
          .backgroundColor('#07C160')  // 微信绿
          //.textStyle({ color: '#ffffff' })
          .onClick(() => {
            router.back()
          })
      }
      .margin({ top: 8, left: 12, right: 12, bottom: 8 })  // 整体外边距
      .height(50)  // 合适的高度
      .backgroundColor('#f5f5f5')  // 浅灰背景
      .alignItems(VerticalAlign.Center)  // 垂直居中对齐
      .width('100%')
    }
  }
}

04-27
### WPF-UI Framework Usage Examples and Features #### Data Binding in WPF WPF provides robust data binding capabilities, allowing developers to bind UI elements directly to data sources. For instance, the `DataGrid` control supports advanced editing scenarios through its integration with the `IEditableObject` interface[^2]. When implementing custom business objects, one must explicitly define how these objects handle transactions by implementing this interface. Here’s an example demonstrating basic data binding using a simple ViewModel: ```csharp public class Person : INotifyPropertyChanged, IEditableObject { private string _name; public string Name { get => _name; set { if (_name != value) { _name = value; OnPropertyChanged(nameof(Name)); } } } public void BeginEdit() { // Save current state before edits begin. } public void CancelEdit() { // Restore original values upon cancellation. } public void EndEdit() { // Commit changes after successful edit completion. } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ``` This code snippet illustrates how to create a model that adheres to both `INotifyPropertyChanged` for property change notifications and `IEditableObject` for transactional updates within grids like `DataGrid`. #### Event Aggregation Pattern in WPF Applications For decoupled communication between components in large-scale applications built on top of WPF, leveraging patterns such as Event Broker from Composite UI Application Block (CAB) or Event Aggregator from Prism becomes essential[^1]. These mechanisms allow loosely coupled parts of an application to communicate without direct references to each other. Below is an illustrative implementation utilizing Prism's `EventAggregator` service: ```csharp using Prism.Events; // Define a Pub/Sub message type public class MessagePublishedEvent : PubSubEvent<string> { } // Publisher side logic var ea = Container.Resolve<IEventAggregator>(); ea.GetEvent<MessagePublishedEvent>().Publish("Message sent!"); // Subscriber side logic ea.GetEvent<MessagePublishedEvent>().Subscribe(message => { Console.WriteLine($"Received: {message}"); }); ``` In this case, publishers send messages while subscribers listen for them asynchronously, promoting separation of concerns across modules. #### Custom Controls Development Developers often extend default controls provided out-of-the-box by creating derived classes tailored specifically towards their needs. Below shows extending Button behavior adding extra properties useful during runtime configuration dynamically. ```xml <Window x:Class="CustomControlExample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <!-- Example usage --> <local:ExtendedButton Content="Click Me!" IsEnabledDynamicBinding="{Binding Path=SomeCondition}" /> </StackPanel> </Window> <!-- Code Behind Definition --> public class ExtendedButton : Button { public static readonly DependencyProperty IsEnabledDynamicBindingProperty = DependencyProperty.RegisterAttached( "IsEnabledDynamicBinding", typeof(bool), typeof(ExtendedButton)); public bool IsEnabledDynamicBinding { get { return (bool)this.GetValue(IsEnabledDynamicBindingProperty); } set { this.SetValue(IsEnabledDynamicBindingProperty, value); } } } ``` Such extensions provide flexibility enabling richer interactions based entirely around declaratively defined attributes inside XAML markup files themselves rather than procedural coding approaches elsewhere outside views altogether.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值