一、跨平台UI的「三座大山」
1.1 传统UI开发:像在玩「多语言翻译」
给Windows写个按钮:
<Button Content="点击我" />
给Mac写个按钮:
<Button Title="点我呀" />
给iOS写个按钮:
UIButton *btn = [[UIButton alloc] init];
...
最后发现:
代码像「八国联军」,维护堪比拆炸弹!
1.2 现代解决方案:用模式造「万能翻译器」
C#跨平台UI的核心 = 设计模式 + 平台适配层,
就像给UI装了个「多语言脑机接口」,
自动说:“我要变成Mac风格,但代码还是C#!”
二、主流设计模式:UI界的「变形金刚」
2.1 MVVM模式:给UI装个「智能大脑」
Model(数据层)→ ViewModel(逻辑层)→ View(显示层)
就像给UI加了个「翻译官」,
数据变化自动同步,
代码像「乐高积木」一样可拼装!
代码示例:MVVM基础结构
// ViewModel层:
public class MainViewModel : INotifyPropertyChanged
{
private string _title;
public string Title
{
get => _title;
set
{
_title = value;
OnPropertyChanged(); // 通知View更新
}
}
public ICommand ChangeTitleCommand => new Command(() =>
{
Title = $"当前平台:{DeviceInfo.Platform}"; // 自动适配平台
});
// 事件通知实现
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
// View层(XAML):
<Label Text="{Binding Title}" />
<Button Text="切换标题" Command="{Binding ChangeTitleCommand}" />
程序员的冷笑话:
为什么MVVM模式最受欢迎?
因为它让View和Model「永不相见」!
2.2 MVU模式:用函数式编程造「UI乐高」
Model(数据)→ View(UI组件)→ Update(状态更新)
就像给UI装了个「自动拼图」,
每次点击按钮自动重新渲染,
代码像「数学公式」一样优雅!
代码示例:MVU模式实现计数器
// Model层:
public record CounterState(int Count);
// View层:
public static Func<CounterState, IView> View = state =>
new VStack {
new Label(state.Count.ToString()),
new Button("点我", () => Program.Dispatch(CounterAction.Increment))
};
// Update层:
public static CounterState Update(CounterState state, CounterAction action) =>
action switch
{
CounterAction.Increment => state with { Count = state.Count + 1 },
_ => state
};
灵魂拷问:
为什么MVU模式像「数学考试」?
因为它要求你写出「完美函数」!
三、平台适配:让UI像「变色龙」一样融合适配
3.1 基础适配:用条件编译造「多语言翻译器」
// 用条件编译实现平台特有功能:
#if __IOS__
// iOS专属代码:
var statusBar = UIApplication.SharedApplication.StatusBarFrame.Height;
#elif __ANDROID__
// Android专属代码:
var actionBar = FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar);
#endif
程序员的哲学:
这段代码像在说:
“我看到你是iOS,我给你加个圆角!
哦,你是Android?那我加个阴影!”
3.2 响应式布局:用FlexLayout造「变形金刚」
// 在XAML中使用FlexLayout自动适配:
<FlexLayout Direction="Row" Wrap="Wrap">
<Button Text="按钮1" FlexLayout.Grow="1" />
<Button Text="按钮2" FlexLayout.Grow="2" />
</FlexLayout>
程序员的浪漫:
这段代码让布局像「橡皮泥」,
屏幕变大就撑开,屏幕变小就折叠!
四、优化技巧:让UI「跑得比风还快」
4.1 避免UI卡顿:用异步加载造「缓冲气垫」
// 在ViewModel中异步加载数据:
public async Task LoadData()
{
IsLoading = true;
await Task.Delay(2000); // 模拟网络请求
Items = await GetItemsFromAPI();
IsLoading = false;
}
程序员的吐槽:
这就像给UI装了个「缓冲气垫」,
防止用户看到「转圈圈」直接崩溃!
4.2 资源管理:用平台适配器造「万能工具箱」
// 自定义资源适配器:
public class PlatformAdapter
{
public static ImageSource GetImage(string name)
{
#if __IOS__
return ImageSource.FromFile($"ios_{name}.png");
#elif __ANDROID__
return ImageSource.FromFile($"drawable/android_{name}.png");
#else
return ImageSource.FromFile(name + ".png");
#endif
}
}
程序员的智慧:
这段代码让资源像「变形金刚」,
自动选择平台专属图片!
五、实战案例:用C#代码征服「四国联军」
5.1 场景:开发一个跨平台「天气应用」
需求:
- 支持Windows/Mac/iOS/Android
- 自动适配平台UI风格
- 实时显示天气数据
5.2 解决方案:MVVM+平台适配组合拳
// ViewModel层(核心逻辑):
public class WeatherViewModel : INotifyPropertyChanged
{
public async Task LoadWeather()
{
var weather = await WeatherAPI.GetWeather();
Temperature = weather.Temperature;
Description = weather.Description;
}
}
// View层(XAML):
<ContentView>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Text="当前温度:" Grid.Row="0" />
<Label Text="{Binding Temperature}" Grid.Row="1" />
</Grid>
</ContentView>
// 平台适配层:
// iOS专属:
public partial class WeatherPage : ContentPage
{
public WeatherPage()
{
// 添加iOS导航栏样式
NavigationPage.SetPrefersLargeTitles(this, true);
}
}
事后复盘:
这个应用在四平台完美适配,
代码重复率降低80%,
而且维护成本像「喝奶茶」一样轻松!
六、防坑指南:避免UI设计的「四大天坑」
6.1 坑位1:直接写平台特有代码,像「用锤子修表」
反例:在ViewModel中直接调用iOS的UIAlertView
正确姿势:用依赖注入注入平台适配接口
6.2 坑位2:忽略性能优化,像「给跑车装铅块」
反例:在UI线程中执行耗时操作
正确姿势:用async/await+异步编程